Python Programming/Collection
Python Programming
[edit | edit source]Learning Guide
[edit | edit source]This learning guide supports the Wikiversity course Python Programming, available at http://en.wikiversity.org/wiki/Python_Programming.
Overview
[edit | edit source]Python Programming/Collection/Sidebar Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Python supports many programming paradigms, including object-oriented, functional, and procedural programming. Its design philosophy emphasizes code readability, simplicity, and its syntax allows programmers to express concepts in fewer lines of code than possible in other popular programming languages. Python is very extensible and the modularity of this language has made it popular for adding interfaces to existing applications.[1]
This course comprises 16 lessons on Python programming using Python 3. Each lesson includes a combination of Wikipedia and Internet-based readings, YouTube videos, and hands-on learning activities.
Preparation
[edit | edit source]This is a second-semester, college-level course. Learners should already be familiar with introductory computer concepts and have advanced or proficient-level computer skills.
Lessons
[edit | edit source]- Introduction
- Variables
- Conditions
- Loops
- Functions
- Strings
- Lists
- Dictionaries
- Tuples and Sets
- Classes
- Modules
- RegEx
- Files
- Internet Data
- Databases
- GUI
See Also
[edit | edit source]- Computer Programming
- Python
- Python Concepts
- Wikipedia: Python (programming language)
- Wikibooks: Python Programming
- PythonLearn.com
- Microsoft MVA: Introduction to Programming with Python
- Open Book Project: Beginning Python Programming
- Digital Ocean: How to Code in Python3
- Interactive Python: How to Think Like a Computer Scientist
- PracticePython.org
- WsCube Tech Python Tutorial
- AutomateTheBoringStuff.com Python Book
- FutureLearn: Programming 101: An Introduction to Python for Educators
Participation
[edit | edit source]This section is for the purpose of optionally documenting one's participation process in the course. Here might be notes by learners who might document their learning process and how they view the learning materials and/or how they interacted with them, contributed content or ideas regarding interacting with it. It may include participants experiences with material. Their motivation reasons for participating in the course as a whole and for parts of the course.
Bibliography
[edit | edit source]- Severance, C. (2013). Python for Informatics: Exploring Information
- Severance, C. (2016). Python for Everybody
References
[edit | edit source]Lesson 1 - Introduction
[edit | edit source]This lesson introduces the Python programming language and environment.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Introduction
- Need and evolution of Python
- Features of Python
- The Prompt
- Editor and source file
- Translation and executable
- Installation
- Windows and Linux installation
Readings
[edit | edit source]- Wikipedia: Python (programming language)
- Wikipedia: Integrated development environment
- Wikipedia: IDLE (Python)
- Python for Everyone: Why should you learn to write programs?
Multimedia
[edit | edit source]- YouTube: Python for Informatics: Chapter 1 - Introduction by Chuck Severance
- YouTube: Python Programming by Derek Banas
- YouTube: Installing Python by thenewboston
- YouTube: Installing PyCharm by thenewboston
- YouTube: Python Basics Playlist (21 videos) by John Philip Jones
- YouTube: Learn Python - Full Course for Beginners by freeCodeCamp.org
Examples
[edit | edit source]Comments
[edit | edit source]A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line.[2]
# This is a comment
The print function prints objects to standard output or to a text stream.[3]
# This script demonstrates a Python print statement.
print("Hello Wikiversity!")
Exit
[edit | edit source]The exit function exits from Python.[4]
exit()
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- W3Schools
- Wikiversity
- Wikibooks
Python
[edit | edit source]- Learn the differences between Python 2 and Python 3.
- Download and install Python.
- Review TutorialsPoint: Python 3 Environment Setup.
- Download Python from Python.org: Downloads.
- Install Python.
- At a command prompt or terminal window, run the command
python -V
orpython3 -V
to confirm Python installation and display the version number.
- Use the Python interpreter.
- At a command prompt or terminal window, run the command
python
orpython3
to start the Python interpreter. - At the Python prompt, enter
print("Hello <name>!")
, replacing<name>
with your name. - At the Python prompt, enter
exit()
to exit Python.
- At a command prompt or terminal window, run the command
Python IDEs
[edit | edit source]- Use the Python IDLE integrated development environment.
- Review Wikipedia: IDLE (Python).
- Run IDLE on your system.
- At the Python prompt, enter
print("Hello <name>!")
, replacing<name>
with your name. - At the Python prompt, enter
exit()
to exit IDLE.
- Download and install another Python integrated development environment (IDE).
- Review TechAltair: 7 Best Python IDE for Pythonist.
- Select and download one of the recommended Python IDEs. Chose PyCharm Community Edition if you are unsure which one to select.
- Install the IDE.
- Run the IDE.
- In a new file, enter
print("Hello <name>!")
, replacing<name>
with your name. - Save the file as hello.py.
- Run the script and observe the results.
- Exit the IDE.
- Use a free cloud-based Python IDE.
- Review Wikipedia: Cloud9 IDE.
- Create a free account at Cloud9.
- Using Cloud9, create a new private workspace. Name the workspace whatever you like, or use
python
. Choose Python as the workspace template. - Once the workspace starts, examine the Cloud9 IDE.
- Cloud9 has both Python 2 and Python 3 installed. At the bash prompt, run the command
python
to start the Python 2 interpreter. - At the Python prompt, enter
print("Hello <name>!")
, replacing<name>
with your name. - At the Python prompt, enter
exit()
to exit Python. - At the bash prompt, run the command
python3
to start the Python 3 interpreter. - At the Python prompt, enter
print("Hello <name>!")
, replacing<name>
with your name. - At the Python prompt, enter
exit()
to exit Python. - Create a new file in the Cloud9 IDE.
- In the new file, enter
print("Hello <name>!")
, replacing<name>
with your name. - Save the file as hello.py.
- Run the script and observe the results.
- In the lower Run window, change the Runner to Python 3.
- Run the script and observe the results.
- To set Python 3 as the default runner, use Run / Run Configurations / Manage and set Python Version to Python 3.
- Exit Cloud9.
Games
[edit | edit source]- Play CodeCombat Kithgard Dungeon levels 1 - 4.
Documentation
[edit | edit source]- Read stackoverflow python questions: https://stackoverflow.com/questions/tagged/python?tab=Votes
Lesson Summary
[edit | edit source]- Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[5]
- A high-level programming language is a programming language with strong abstraction from the details of the computer.[6]
- An interpreted language is a programming language for which most of its implementations execute instructions directly, without previously compiling a program into machine-language instructions.[7]
- There are three major versions of Python (1.x, 2.x, and 3.x). Python 2 and Python 3 are both considered current, stable languages. Python 3 is not backward-compatible with Python 2.[8]
- Most Python implementations support a command-line interface / command-line interpreter in which users may enter statements sequentially and receive the results immediately. This sequence is known as a read–eval–print loop (REPL).[9]
- The Python interpreter may also execute scripts, which are collections of Python source code saved as a file or files.[10]
- A variety of Integrated Development Environments (IDEs) are available for Python. IDEs normally consist of a source code editor, build automation tools, and a debugger. Most modern IDEs also have intelligent code completion.[11]
- IDLE (Integrated DeveLopment Environment) is an integrated development environment for Python, which has been bundled with the default implementation of the language since 1.5.2b1.[12]
- A Python comment starts with a hash character (
#
) that is not part of a string literal, and ends at the end of the physical line.[13] - The
print()
function prints objects to standard output or to a text stream.[14] - The
exit()
function exits from Python.[15] - Python files use the filename extension
.py
.[16]
Key Terms
[edit | edit source]- bug
- An error in a program.[17]
- central processing unit
- The heart of any computer. It is what runs the software that we write; also called “CPU” or “the processor”.[18]
- compile
- To translate a program written in a high-level language into a low-level language all at once, in preparation for later execution.[19]
- high-level language
- A programming language like Python that is designed to be easy for humans to read and write.[20]
- interactive mode
- A way of using the Python interpreter by typing commands and expressions at the prompt.[21]
- interpret
- To execute a program in a high-level language by translating it one line at a time.[22]
- low-level language
- A programming language that is designed to be easy for a computer to execute; also called “machine code” or “assembly language”.[23]
- machine code
- The lowest-level language for software, which is the language that is directly executed by the central processing unit (CPU).[24]
- main memory
- Stores programs and data. Main memory loses its information when the power is turned off.[25]
- parse
- To examine a program and analyze the syntactic structure.[26]
- portability
- A property of a program that can run on more than one kind of computer.[27]
- print statement
- An instruction that causes the Python interpreter to display a value on the screen.[28]
- problem solving
- The process of formulating a problem, finding a solution, and expressing the solution.[29]
- program
- A set of instructions that specifies a computation.[30]
- prompt
- When a program displays a message and pauses for the user to type some input to the program.[31]
- secondary memory
- Stores programs and data and retains its information even when the power is turned off. Generally slower than main memory. Examples of secondary memory include disk drives and flash memory in USB sticks.[32]
- semantics
- The meaning of a program.[33]
- semantic error
- An error in a program that makes it do something other than what the programmer intended.[34]
- source code
- A program in a high-level language.[35]
Review Questions
[edit | edit source]-
Python is _____.Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.
-
A high-level programming language is _____.A high-level programming language is a programming language with strong abstraction from the details of the computer.
-
An interpreted language is _____.An interpreted language is a programming language for which most of its implementations execute instructions directly, without previously compiling a program into machine-language instructions.
-
There are _____ major versions of Python. They are _____.There are three major versions of Python. They are 1.x, 2.x, and 3.x.
-
Python 2 and Python 3 are both considered _____.Python 2 and Python 3 are both considered current, stable languages.
-
Python 3 is _____-compatible with Python 2.Python 3 is not backward-compatible with Python 2.
-
Most Python implementations support a command-line interface / command-line interpreter in which ____. This sequence is known as a ____.Most Python implementations support a command-line interface / command-line interpreter in which users may enter statements sequentially and receive the results immediately. This sequence is known as a read–eval–print loop (REPL).
-
The Python interpreter may also execute _____.The Python interpreter may also execute scripts, which are collections of Python source code saved as a file or files.
-
A variety of _____ (IDEs) are available for Python. IDEs normally consist of _____, _____ and _____. Most modern IDEs also have _____.A variety of Integrated Development Environments (IDEs) are available for Python. IDEs normally consist of a source code editor, build automation tools and a debugger. Most modern IDEs also have intelligent code completion.
-
IDLE (Integrated DeveLopment Environment) is _____.IDLE (Integrated DeveLopment Environment) is an integrated development environment for Python, which has been bundled with the default implementation of the language since 1.5.2b1.
-
A Python comment starts with _____, and ends _____.A Python comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line.
-
The print() function _____.The print() function prints objects to standard output or to a text stream.
-
The exit() function _____.The exit() function exits from Python.
-
Python files use the filename extension _____.Python files use the filename extension .py.
-
The difference between a high-level and low-level programming language is _____.A high-level programming language is easy for humans to understand, while a low-level programming language is harder to understand by a programmer but runs faster.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python - Introduction
- Quiz: Quizlet: Python - Introduction
See Also
[edit | edit source]- Python.org: Using the Python Interpreter
- Python basics - tutorial with exercises
- SoloLearn: Python
- Open Book Project: Python 3 - The way of the program
- PEP8 Online: Python Formatting
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Lexical analysis
- ↑ Python.org: Built-in Functions
- ↑ Python.org: System-specific parameters and functions
- ↑ Wikipedia:Python (programming language)
- ↑ Wikipedia: High-level programming language
- ↑ Wikipedia: Interpreted language
- ↑ Wikipedia:Python (programming language)
- ↑ Wikipedia:Python (programming language)
- ↑ Wikipedia: Scripting language
- ↑ Wikipedia: Integrated development environment
- ↑ Wikipedia: IDLE (Python)
- ↑ Python.org: Lexical analysis
- ↑ Python.org: Built-in Functions
- ↑ Python.org: System-specific parameters and functions
- ↑ Wikipedia:Python (programming language)
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
- ↑ PythonLearn: Why should you learn to write programs?
Lesson 2 - Variables
[edit | edit source]This lesson introduces variables, expressions, and statements.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Language Basics
- Language elements (constants, numbers and strings)
- Strings types (single quotes, double quotes and triple quotes)
- Escape Sequence, string concatenation and format method
- Variables naming, types and objects
- Indentation, logical and physical lines
- Operators and Expressions
- Operators and Expressions
- Evaluation Order and Associativity
- Input Output
- User input
Readings
[edit | edit source]- Wikipedia: Variable (computer science)
- Wikipedia: Data type
- Wikipedia: Expression (computer science)
- Wikipedia: Statement (computer science)
- Wikipedia: Order of operations
- Python for Everyone: Variables, expressions, and statements
Multimedia
[edit | edit source]- YouTube: Python for Informatics: Chapter 2 - Expressions
- YouTube: Python Numbers
- YouTube: Python3 Input & Output
- Youtube: Python 3 Programming Tutorial: Variables
- Youtube: Setting up Pycharm and getting started
Examples
[edit | edit source]Data Types
[edit | edit source]Built-in Python data types include integer (int), floating point (float), string (str), and Boolean (bool) data types.[2]
value = 1 + 1
print(value) # Displays 2
print(type(value)) # Displays <type 'int'>
value = 0.1 + 0.1
print(value) # Displays 0.2
print(type(value)) # Displays <type 'float'>
value = '1' + '1'
print(value) # Displays 11
print(type(value)) # Displays <type 'str'>
value = True
print(value) # Displays True
print(type(value)) # Displays <type 'bool'>
Type Conversion
[edit | edit source]An object’s type is accessed by the built-in function type().[3]
value = 1.9
print(value) # Displays 1.9
print(type(value)) # Displays <type 'float'>
value = int(value)
print(value) # Displays 1
print(type(value)) # Displays <type 'int'>
value = 1
print(value) # Displays 1
print(type(value)) # Displays <type 'int'>
value = float(value)
print(value) # Displays 1.0
print(type(value)) # Displays <type 'float'>
value = 1
print(value) # Displays 1
print(type(value)) # Displays <type 'int'>
value = str(value)
print(value) # Displays 1
print(type(value)) # Displays <type 'str'>
Quotes
[edit | edit source]String literals are written in a variety of ways, including single quotes, double quotes, and triple quotes. Triple quoted strings may span multiple lines.[4] The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.[5]
value = 'single quotes'
print(value)
value = "double quotes"
print(value)
value = \
'''triple quotes
span multiple lines'''
print(value)
value = '"nested quotes"'
print(value)
value = "'nested quotes'"
print(value)
value = "\"escape character quotes\nand multiple lines\""
print(value)
Numeric Operations
[edit | edit source]All numeric types (except complex) support the following operations, sorted by ascending priority.[6]
a = 3
b = 2
print(a + b) # 5
print(a - b) # 1
print(a * b) # 6
print(a / b) # 1.5
print(a // b) # 1
print(a % b) # 1
print(-a) # -3
print(a ** b) # 9
Assignment Operations
[edit | edit source]An assignment statement evaluates the expression and assigns the result to the target. Augmented assignment is the combination, in a single statement, of an operation and an assignment statement.[7]
a = 3
b = 2
a += b # a = 5
a -= b # a = 3
a *= b # a = 6
a /= b # a = 1.5
a //= b # a = 1
a %= b # a = 1.0
a **= b # a = 9
Input Function
[edit | edit source]Python 2: If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), which is then parsed and evaluated as a Python expression.[8]
Python 3: If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.[9]
input([prompt])
#Python 2
value = input("Enter a numeric value: ")
print("You entered " + str(value))
value = input('Enter a string value in "quotes": ')
print("You entered " + value)
#Python 3
value = input("Enter a value: ")
print("You entered a string value " + value)
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- SoloLearn
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- Experiment with different numeric operations to ensure you understand how they work. Then review either MathsIsFun: Order of Operations or Teachoo: What is BODMAS?. Create a Python program that demonstrates the order of operations.
- Create a Python program to prompt the user for hours and rate per hour to compute gross pay (hours * rate).[10]
- Review MathsIsFun: Conversion of Temperature. Create a Python program that asks the user for a Fahrenheit temperature and then calculate and display the corresponding Celsius temperature or ask the user for a Celsius temperature and then calculate and display the corresponding Fahrenheit temperature.
- Create a Python program that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds.
- Review MathsIsFun: Area of Plane Shapes. Create a Python program that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes.
Games
[edit | edit source]- Play CodeCombat.
Lesson Summary
[edit | edit source]- Built-in Python data types include integer (
int()
), floating point (float()
), string (str()
), and Boolean (bool()
).[11] - An object’s type is accessed by the built-in function
type()
.[12] - String literals are written in a variety of ways, including single quotes, double quotes, and triple quotes. Triple quoted strings may span multiple lines.[13]
- The backslash (
\
) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.[14] - Numeric operators include
+
,-
,*
,/
,//
,%
, and**
.[15] - Assignment operators include
+=
,-=
,*=
,/=
,//=
,%=
, and**=
.[16] - The Python 2
input()
function reads a line from input, converts it to a string (stripping a trailing newline), which is then parsed and evaluated as a Python expression.[17] - The Python 3
input()
function reads a line from input, converts it to a string (stripping a trailing newline), and returns that.[18]
Key Terms
[edit | edit source]- assignment
- A statement that assigns a value to a variable.[19]
- concatenate
- To join two operands end to end.[20]
- comment
- Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.[21]
- escape character
- A character which invokes an alternative interpretation on subsequent characters in a character sequence.[22]
- evaluate
- To simplify an expression by performing the operations in order to yield a single value.[23]
- expression
- A combination of variables, operators, and values that represents a single result value.[24]
- floating point
- A type that represents numbers with fractional parts.[25]
- floor division
- The operation that divides two numbers and chops off the fractional part.[26]
- integer
- A type that represents whole numbers.[27]
- keyword
- A reserved word that is used by the compiler to parse a program; you cannot use keywords like if, def, and while as variable names.[28]
- mnemonic
- A memory aid. We often give variables mnemonic names to help us remember what is stored in the variable.[29]
- modulus operator
- An operator, denoted with a percent sign (%), that works on integers and yields the remainder when one number is divided by another.[30]
- operand
- One of the values on which an operator operates.[31]
- operator
- A special symbol that represents a simple computation like addition, multiplication, or string concatenation.[32]
- rules of precedence
- The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.[33]
- statement
- A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.[34]
- string
- A type that represents sequences of characters.[35]
- type
- A category of values. The types we have seen so far are integers (type int), floating-point numbers (type float), and strings (type str).[36]
- value
- One of the basic units of data, like a number or string, that a program manipulates.[37]
- variable
- A name that refers to a value.[38]
Review Questions
[edit | edit source]-
Built-in Python data types include _____, _____, _____, and _____.Built-in Python data types include integer (int()), floating point (float()), string (str()), and Boolean (bool()).
-
An object’s type is accessed by the built-in function _____.An object’s type is accessed by the built-in function type().
-
String literals are written in a variety of ways, including _____, _____, and _____. _____ may span multiple lines.String literals are written in a variety of ways, including single quotes, double quotes, and triple quotes. Triple quoted strings may span multiple lines.
-
The _____ character is used to escape characters that otherwise have a special meaning, such as _____.The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
-
Numeric operators include _____.Numeric operators include +, -, *, /, //, %, and **.
-
Assignment operators include _____.{{{2}}}
-
The Python 2 input() function _____.The Python 2 input() function reads a line from input, converts it to a string (stripping a trailing newline), which is then parsed and evaluated as a Python expression.
-
The Python 3 input() function _____.The Python 3 input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Variables
- Flashcards: Quizlet: Python Variable Types
- Flashcards: Quizlet: Python Variables, Expressions, and Statements
- Quiz: Quizlet: Python Variables
- Quiz: Quizlet: Python Variable Types
- Quiz: Quizlet: Python Variable, Expressions, and Statements
See Also
[edit | edit source]- Python.org: An Informal Introduction to Python
- Python.org: Built-in Types
- Python.org: Expressions
- Python.org: Data model
- Python.org: Simple statements
- SoloLearn: Python
- Open Book Project: Python 3 - Variables, expressions and statements
- Digital Ocean: How to use Variables in Python 3
- PythonBasics: variables
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Lexical analysis
- ↑ Python.org: Built-in Types
- ↑ Python.org: Simple Statements
- ↑ Python.org: Built-in Functions
- ↑ Python.org: Built-in Functions
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ Python.org Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Lexical analysis
- ↑ Python.org: Built-in Types
- ↑ Python.org: Simple Statements
- ↑ Python.org: Built-in Functions
- ↑ Python.org: Built-in Functions
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ Wikipedia: Escape character
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ PythonLearn: Variables, expressions, and statements
Lesson 3 - Conditions
[edit | edit source]This lesson introduces conditions and exception handling.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Control Flow
- The if statement
- Exceptions
- Errors and exceptions
- Handling and raising Exceptions
- Try, Finally and the with statement
Readings
[edit | edit source]- Wikipedia: Conditional (computer programming)
- Wikipedia: Exception handling
- Python for Everyone: Conditional execution
Multimedia
[edit | edit source]- YouTube: Python Tutorial for Beginners 6: Conditionals and Booleans - If, Else, and Elif Statements
- YouTube: Python for Informatics - Chapter 3 - Conditional Execution
- YouTube: If, Then, Else in Python
- YouTube: Python if elif else
- YouTube: How to Use If Else Statements in Python
Examples
[edit | edit source]Comparison Operations
[edit | edit source]There are eight comparison operations in Python.[2]
a = 3
b = 2
print(a == b) # False
print(a != b) # True
print(a < b) # False
print(a > b) # True
print(a <= b) # False
print(a >= b) # True
print(a is b) # False
print(a is not b) # True
Boolean Operations
[edit | edit source]The Boolean operations include and, or, and not.[3]
a = 3
b = 2
print(a < b and b < a) # False
print(a < b or b < a) # True
print(a < b) # False
print(not(a < b)) # True
Bitwise Operations
[edit | edit source]Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value.[4]
a = 5
b = 3
print(bin(a)) # 0101
print(bin(b)) # 0011
print(bin(a & b)) # 0001
print(bin(a | b)) # 0111
print(bin(a ^ b)) # 0110
print(bin(~a)) # -0110
print(bin(a << b)) # 101000
print(bin(a >> b)) # 000000
If Statement
[edit | edit source]An if statement may contain zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.[5]
input = input("Is it morning (m), afternoon (a), or evening (e)? ")
if input == "m":
print("Good morning!")
elif input == "a":
print("Good afternoon!")
elif input == "e":
print("Good evening!")
else:
print("Hello!")
Try Statement
[edit | edit source]The try statement executes the try clause. If no exception occurs, the except clause is skipped. If an exception occurs during execution of the try clause, the except clause is executed, and then execution continues after the try statement.[6]
try:
value = input("Enter a numeric value: ")
result = 1 / float(value)
print("1 / " + value + " = " + str(result))
except:
print("An error occurred dividing 1 by " + value + "!")
Except Statement
[edit | edit source]A try statement may have more than one except clause, to specify handlers for different exceptions.[7]
try:
value = input("Enter a numeric value: ")
result = 1 / float(value)
print("1 / " + value + " = " + str(result))
except ValueError as error:
print(value + " is not a numeric value!")
except ZeroDivisionError as error:
print("Cannot divide by 0!")
except:
print("An unexpected error occurred dividing 1 by " + value + "!")
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- Review Python.org: Truth Value Testing. Create a Python program that uses different values and conditions to confirm that in Python zero is false and anything non-zero is true. Also show that the explicit value of False is 0 and the explicit value of True is 1.
- Create a Python program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use an if/elif/else statement to display their approximate age in the selected timeframe.
- Create a Python program to prompt the user for hours and rate per hour to compute gross pay (hours * rate). Include a calculation to give 1.5 times the hourly rate for any overtime (hours worked above 40 hours).[8]
- Review MathsIsFun: Conversion of Temperature. Create a Python program that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use an if/elif/else statement to determine their selection and then gather the appropriate input and calculate and display the converted temperature.
- Review MathsIsFun: Area of Plane Shapes. Create a Python program that asks the user what shape they would like to calculate the area for. Use an if/elif/else statement to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
- Extend one or more of the programs above by adding a try/except block to handle any runtime errors caused by the user entering invalid values for the input.
Games
[edit | edit source]- Play CodeCombat.
Lesson Summary
[edit | edit source]Condition Concepts
[edit | edit source]- Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.[9]
- The pseudocode structure of a conditional statement is:[10]
IF (boolean condition) THEN (consequent) ELSE (alternative) END IF
- If the condition is true, the statements following the
THEN
are executed. Otherwise, the execution continues in the following branch – either in theELSE
block (which is usually optional), or if there is noELSE
branch, then after theEND IF
.[11] - By using
ELSE IF
/ELSEIF
, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.[12] - Exception handling is the process of responding to the occurrence, during computation, of anomalous or exceptional events requiring special processing, often changing the normal flow of program execution.[13]
- In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote a data structure storing information about an exceptional condition.[14]
- One mechanism to transfer control, or raise an exception, is known as a throw.[15]
- The scope for exception handlers starts with a "try" clause.[16]
- An exception is said to be thrown and execution is transferred to a "catch" or "except" statement.[17][18]
Python Conditions
[edit | edit source]- The Python syntax for a conditional statement is:[19]
if <condition>: <statements> elif <condition>: <statements> else: <statements>
- An if statement may contain zero or more elif parts, and the else part is optional.[20]
- An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.[21]
- There are eight comparison operations in Python, including ==, !=, <, >, <=, >=, is, is not.[22]
- There are three Boolean operations in Python, including and, or, not.[23]
- There are six bitwise operations in Python, including &, |, ^, ~, <<, >>.[24]
- Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value.[25]
- The Python syntax for a try statement is:[26]
try: <statements> except <exception>: <statements> except: <statements>
- The try statement executes the try clause. If f no exception occurs, the except clause is skipped. If an exception occurs during execution of the try clause, the except clause is executed, and then execution continues after the try statement.[27]
- A try statement may have more than one except clause, to specify handlers for different exceptions.[28]
Key Terms
[edit | edit source]- body
- The sequence of statements within a compound statement.[29]
- boolean expression
- An expression whose value is either True or False.[30]
- branch
- One of the alternative sequences of statements in a conditional statement.[31]
- chained conditional
- A conditional statement with a series of alternative branches.[32]
- comparison operator
- One of the operators that compares its operands ==, !=, >, <, >=, and <=.[33]
- conditional statement
- A statement that controls the flow of execution depending on some condition.[34]
- condition
- The boolean expression in a conditional statement that determines which branch is executed.[35]
- compound statement
- A statement that consists of a header and a body. The header ends with a colon (). The body is indented relative to the header.[36]
- guardian pattern
- Where we construct a logical expression with additional comparisons to take advantage of the short-circuit behavior.[37]
- logical operator
- One of the operators that combines boolean expressions and, or, and not.[38]
- nested conditional
- A conditional statement that appears in one of the branches of another conditional statement.[39]
- traceback
- A list of the functions that are executing, printed when an exception occurs.[40]
- short circuit
- When Python is part-way through evaluating a logical expression and stops the evaluation because Python knows the final value for the expression without needing to evaluate the rest of the expression.[41]
Review Questions
[edit | edit source]-
Conditional statements are features of a programming language which _____.Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.
-
The pseudocode structure of a conditional statement is:The pseudocode structure of a conditional statement is:
IF (boolean condition) THEN
(consequent)
ELSE
(alternative)
END IF -
If a condition is true, _____. Otherwise, the execution continues _____.If the condition is true, the statements following the THEN are executed. Otherwise, the execution continues in the following branch – either in the ELSE block (which is usually optional), or if there is no ELSE branch, then after the END IF.
-
By using ELSE IF/ELSEIF, it is possible to _____.By using ELSE IF/ELSEIF, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.
-
Exception handling is the process of _____.Exception handling is the process of responding to the occurrence, during computation, of anomalous or exceptional events requiring special processing, often changing the normal flow of program execution.
-
In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote _____.In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote a data structure storing information about an exceptional condition.
-
One mechanism to transfer control, or raise an exception, is known as _____.One mechanism to transfer control, or raise an exception, is known as a throw.
-
The scope for exception handlers starts with _____.The scope for exception handlers starts with a "try" clause.
-
An exception is said to be thrown and execution is transferred to _____.An exception is said to be thrown and execution is transferred to a "catch" or "except" statement.
-
The Python syntax for a conditional statement is:The Python syntax for a conditional statement is:
if <condition>:
<statements>
elif <condition>:
<statements>
else:
<statements> -
An if statement may contain zero or more _____ parts, and the _____ part is optional.An if statement may contain zero or more elif parts, and the else part is optional.
-
An if ... elif ... elif ... sequence is a substitute for _____ found in other languages.An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
-
There are eight comparison operations in Python, including _____.There are eight comparison operations in Python, including ==, !=, <, >, <=, >=, is, is not.
-
There are three Boolean operations in Python, including _____.There are three Boolean operations in Python, including and, or, not.
-
There are six bitwise operations in Python, including _____.There are six bitwise operations in Python, including &, |, ^, ~, <<, >>.
-
Bitwise operations only make sense for _____. Negative numbers are treated as _____.Bitwise operations only make sense for integers. Negative numbers are treated as their 2’s complement value.
-
The Python syntax for a try statement is:The Python syntax for a try statement is:
try:
<statements>
except <exception>:
<statements>
except:
<statements> -
The try statement executes _____. If f no exception occurs, _____. If an exception occurs during execution _____.The try statement executes the try clause. If f no exception occurs, the except clause is skipped. If an exception occurs during execution of the try clause, the except clause is executed, and then execution continues after the try statement.
-
A try statement may have more than one _____.A try statement may have more than one except clause, to specify handlers for different exceptions.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Conditionals & Control Flow
- Quiz: Quizlet: Python Conditionals & Control Flow
See Also
[edit | edit source]- Python.org: More Control Flow Tools
- Python.org: Errors and Exceptions
- Python.org: Compound statements
- Real Python: Python Conditional Statements
- Open Book Project: Python 3 - Conditionals
- TutorialsPoint: Python If...Elif...Else Statements
- PYDanny: Why Doesn't Python Have Switch Case?
- Flocabulary.com: Conditionals
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: More Control Flow Tools
- ↑ Python.org: Errors and Exceptions
- ↑ Python.org: Errors and Exceptions
- ↑ PythonLearn: Conditional Execution
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Conditional (computer programming)
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Wikipedia: Exception handling
- ↑ Python.org Handling Exceptions
- ↑ Python.org: More Control Flow Tools
- ↑ Python.org: More Control Flow Tools
- ↑ Python.org: More Control Flow Tools
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org Handling Exceptions
- ↑ Python.org: Errors and Exceptions
- ↑ Python.org: Errors and Exceptions
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
- ↑ PythonLearn: Conditional execution
Lesson 4 - Loops
[edit | edit source]This lesson introduces loops.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Control Flow
- The while statement
- The for loop
- The break and continue statement
Readings
[edit | edit source]- Wikipedia: Control flow
- Python for Everyone: Iteration
- Python Basics: Iteration, Iterables, Iterators, and Looping
Multimedia
[edit | edit source]- YouTube: Python for Informatics: Chapter 5 - Iterations
- YouTube: Python For
- YouTube: Python Range and While
- YouTube: Python Break
- YouTube: Python Continue
- YouTube: Python Nested Loops
- YouTube: Python Iteration Playlist
- Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
Examples
[edit | edit source]While Statement
[edit | edit source]The while loop executes as long as the condition remains true. In Python, any non-zero integer value is true and zero is false. The condition may also be a string or list value, in which case anything with a non-zero length is true and empty sequences are false. The body of the loop must be indented, and each line within a block must be indented by the same amount.[2]
i = 0
while i < 3:
print(i) # 0, 1, 2
i += 1
For Statement
[edit | edit source]The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.[3]
for i in range(3):
print(i) # 0, 1, 2
Range Function
[edit | edit source]The range function returns an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops. The syntax for the range function is range([start,] stop[, step])
, with start defaulting to 0 and step defaulting to 1.[4]
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
Break Statement
[edit | edit source]The break statement breaks out of the smallest enclosing for or while loop.[5]
i = 0
while True:
print(i) # 0, 1, 2
i += 1
if i >= 3:
break
Continue Statement
[edit | edit source]The continue statement continues with the next iteration of the loop.[6]
for i in range(10):
if i % 2:
continue
print(i) # 0, 2, 4, 6, 8
Nested Loops
[edit | edit source]Loops may be nested with one loop inside another.[7]
for i in range(1, 4):
for j in range(1, 4):
print(str(i) + str(j), end = '\t')
print()
print()
i = 1
while i < 4:
j = 1
while j < 4:
print(str(i) + str(j), end = '\t')
j += 1
print()
i += 1
Output:
11 12 13 21 22 23 31 32 33 11 12 13 21 22 23 31 32 33
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- SoloLearn
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- Review MathsIsFun: Definition of Average. Create a Python program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores. Include try and except to handle input errors. Revise the program to compare the code required when the loop control structure is based on both while and for statements.
- Create a Python program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. Include try and except to handle input errors. For example, a list of three expressions for the value 1 would be:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
- Review MathsIsFun: 10x Printable Multiplication Table. Create a Python program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Include row and column labels, and include try and except to handle input errors. For example, the output might look like:
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
- Review MathsIsFun: 10x Printable Multiplication Table. Create a Python program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Use a condition with (<variable> % 2) to test for odd or even values. Generate the multiplication table only for even values. For odd values, use the continue statement to continue the next iteration of the loop. Include row and column labels, and include try and except to handle input errors. For example, the output might look like:
2 4 6
2 4 8 12
4 8 16 24
6 12 24 36
- Review MathsIsFun: 10x Printable Multiplication Table. Create a Python program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Use a break statement to terminate the loop if the number of rows or columns exceeds 10. Include row and column labels, and include try and except to handle input errors.
Games
[edit | edit source]- Play CodeCombat.
Lesson Summary
[edit | edit source]Control Flow Concepts
[edit | edit source]- Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.[8]
- Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.[9]
- Python does not support an unconditional branch. All control flow must be structured using conditions, loops. functions, or exit (unconditional halt).[10]
- Python uses colons and indentation to designate code blocks and control structures.[11]
- A loop is a sequence of statements which is specified once but which may be carried out several times in succession.[12]
Python Loops
[edit | edit source]- Python loop structures include while and for.[13]
- While is a condition-controlled loop, repeating until some condition changes.[14]
- Python for loops are collection-controlled loops repeating for all elements of a sequence, which is more like foreach in other programming languages.[15]
- Loops may be continued prematurely using the continue statement.[16]
- Loops may be terminated prematurely using the break statement.[17]
- Programs may be terminated prematurely using the exit() function.[18]
- The while loop executes as long as the condition remains true. In Python, any non-zero integer value is true and zero is false. The condition may also be a string or list value, in which case anything with a non-zero length is true and empty sequences are false.[19]
- The body of the loop must be indented, and each line within a block must be indented by the same amount.[20]
- The syntax for the while loop is:[21]
while condition:
statements
- The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.[22]
- The syntax for the for loop is:[23]
for variable in sequence:
statements
- The range function returns an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.[24]
- The syntax for the range function is
range([start,] stop[, step])
, with start defaulting to 0 and step defaulting to 1.[25] - The break statement breaks out of the smallest enclosing for or while loop.[26]
- The continue statement continues with the next iteration of the loop.[27]
Key Terms
[edit | edit source]- accumulator
- A variable used in a loop to add up or accumulate a result.[28]
- counter
- A variable used in a loop to count the number of times something happened. We initialize a counter to zero and then increment the counter each time we want to “count” something.[29]
- decrement
- An update that decreases the value of a variable.[30]
- initialize
- An assignment that gives an initial value to a variable that will be updated.[31]
- increment
- An update that increases the value of a variable (often by one).[32]
- infinite loop
- A loop in which the terminating condition is never satisfied or for which there is no terminating condition.[33]
- iteration
- Repeated execution of a set of statements using either a function that calls itself or a loop.[34]
Review Questions
[edit | edit source]-
Control flow refers to _____.Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.
-
Control flow statement types include _____, _____, _____, _____, and _____.Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.
-
Python does not support _____. All control flow must be structured using _____.Python does not support an unconditional branch. All control flow must be structured using conditions, loops. functions, or exit (unconditional halt).
-
Python uses _____ to designate code blocks and control structures.Python uses colons and indentation to designate code blocks and control structures.
-
A loop is _____.A loop is a sequence of statements which is specified once but which may be carried out several times in succession.
-
Python loop structures include _____ and _____.Python loop structures include while and for.
-
While is _____.While is a condition-controlled loop, repeating until some condition changes.
-
Python for loops are _____, which is more like _____ in other programming languages.Python for loops are collection-controlled loops repeating for all elements of a sequence, which is more like foreach in other programming languages.
-
Loops may be continued prematurely using the _____ statement.Loops may be continued prematurely using the continue statement.
-
Loops may be terminated prematurely using the _____ statement.Loops may be terminated prematurely using the break statement.
-
Programs may be terminated prematurely using the _____ function.Programs may be terminated prematurely using the exit() function.
-
The while loop executes as long as _____. In Python, _____ is true and _____ is false. The condition may also be _____, in which case _____ is true and _____ are false.The while loop executes as long as the condition remains true. In Python, any non-zero integer value is true and zero is false. The condition may also be a string or list value, in which case anything with a non-zero length is true and empty sequences are false.[18]
-
The body of the loop must be _____.The body of the loop must be indented, and each line within a block must be indented by the same amount.
-
The syntax for the while loop is:The syntax for the while loop is:
while condition:
statements -
The for statement _____.The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
-
The syntax for the for loop is:The syntax for the for loop is:
for variable in sequence:
statements -
The range function _____.The range function returns an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.
-
The syntax for the range function is _____.The syntax for the range function is range([start,] stop[, step]), with start defaulting to 0 and step defaulting to 1.
-
The break statement _____.The break statement breaks out of the smallest enclosing for or while loop.
-
The continue statement _____.The continue statement continues with the next iteration of the loop.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Loops
- Quiz: Quizlet: Python Loops
See Also
[edit | edit source]- Python.org: More Control Flow Tools
- Python.org: Compound statements
- SoloLearn: Python
- Open Book Project: Python 3 - Iteration
- PythonBasics: for loops and exercises
- TutorialsPoint: Python Do While Example
- Digital Ocean: How To Use Break, Continue, and Pass Statements when Working with Loops in Python 3
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: An informal introduction
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: Built-in Types
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ TutorialsPoint: Python nested loops
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Python.org: sys.exit()
- ↑ Python.org: An informal introduction
- ↑ Python.org: An informal introduction
- ↑ Python.org: An informal introduction
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
Lesson 5 - Functions
[edit | edit source]This lesson introduces functions.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Functions
- Function parameters and local variables
- Using global and nonlocal statement
- Default Argument values and keyword arguments
- VarArgs and keyword-only parameters
- The return statement
- DocStrings and annotations
Readings
[edit | edit source]- Wikipedia: Function (computer science)
- Wikipedia: Parameter (computer programming)
- Wikipedia: Recursion (computer science)
- Python for Everyone: Functions
Multimedia
[edit | edit source]- YouTube: Python for Informatics - Chapter 4 - Functions
- YouTube: Python Functions
- YouTube: Python Return Values
- YouTube: Variable Scope
- YouTube: Default Values for Arguments
- YouTube: Keyword Arguments
- YouTube: Flexible Number of Arguments
- YouTube: Python 3 Programming Tutorial - Function Parameters
- YouTube: Python 3.5 Tutorial - Explaining The DocString
- YouTube: How To Use Functions In Python (Python Tutorial #3)
Examples
[edit | edit source]Built-In Functions
[edit | edit source]The Python interpreter has a number of functions and types built into it that are always available.[2]
value = 65
print(bin(value)) # 0b1000001
print(oct(value)) # 0o101
print(hex(value)) # 0x41
print(chr(value)) # A
value = 1234.567
print(round(value, 1)) # 1234.6
print(format(value, ",.2f")) # 1,234.57
User-Defined Functions
[edit | edit source]A function definition defines a user-defined function object.[3] If specified, return leaves the current function call with the expression list (or None) as return value.[4]
def function_1():
print("In function_1")
def function_2(parameter):
print("In function_2 with parameter value:", parameter)
def function_3(parameter):
print("In function_3 with parameter value:", parameter)
return(parameter * 2)
function_1()
function_2("test")
result = function_3("test")
print("function_3 returned", result)
Output:
In function_1 In function_2 with parameter value: test In function_3 with parameter value: test function_3 returned testtest
Local Variables
[edit | edit source]If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.[5]
def local_variable():
value = 1
print("Local value:", value)
def local_parameter(value):
print("Parameter value:", value)
value = 2
print("Parameter value:", value)
local_variable()
try:
print("value:", value)
except:
print("Cannot access local variable.")
value = 1
local_parameter(value)
print("Global value:", value)
Output:
Local value: 1 Cannot access local variable. Parameter value: 1 Parameter value: 2 Global value: 1
Global Variables
[edit | edit source]Variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.[6]
def global_access():
print("Global value:", value)
def global_modification():
global value
value = 2
print("Global value:", value)
value = 1
global_access()
global_modification()
print("Global value:", value)
Output:
Global value: 1 Global value: 2 Global value: 2
Nonlocal Variables
[edit | edit source]The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.[7][8]
global_value = 1
def function():
function_value = 2
def nested_function():
global global_value
nonlocal function_value
global_value = 3
function_value = 4
nested_function()
print("Global value:", global_value)
print("Function value:", function_value)
function()
Output:
Global value: 3 Function value: 4
Parameters
[edit | edit source]A parameter is a named entity in a function definition that specifies an argument that the function can accept.[9] Functions may specify a default value for one or more arguments.[10] Functions may also be called using keyword arguments rather than positional arguments.[11]
def parameters(x = 1, y = 2):
print("x =", x, "y =", y)
parameters()
parameters(3, 4)
parameters(5, 6)
parameters(y = 7, x = 8)
Output:
x = 1 y = 2 x = 3 y = 4 x = 5 y = 6 x = 8 y = 7
Parameter Validation
[edit | edit source]According to the Zen of Python, errors should never pass silently.[12] Parameter validation is automated processing to validate the spelling or accuracy of parameters passed to a function or module.[13]
def function(integer):
if type(integer) is not int:
raise TypeError("Parameter integer must be an integer.")
if integer < 0:
raise ValueError("Parameter integer must be greater than or equal to zero.")
...
Assertions
[edit | edit source]An assertion is a statement that a true–false expression is expected to always be true at that point in the code.[14] The assert statement verifies that an expression is true or it raises an AssertionError. Unlike conditions, which are always executed, assert statements may be disabled when optimization is requested (using command line option -O).[15]
def function(integer):
assert type(integer) is int
assert integer >= 0
...
Variable Arguments
[edit | edit source]Functions may accept a variable number of arguments using the * operator.[16] The variable arguments are provided as a Python list. See Python Programming/Lists for more information.
def sum(*args):
total = 0
for arg in args:
total += arg
return total
print(sum(1, 2, 3, 4))
Output:
10
Variable Named Arguments
[edit | edit source]Variable named arguments may be accessed using the ** operator.[17][18][19] The variable named arguments are provided as a Python dictionary. See Python Programming/Dictionaries for more information.
def keywords(**kwargs):
for item in kwargs.items():
print(item)
keywords(x = 1, y = 2)
Output:
('y', 2) ('x', 1)
Docstring
[edit | edit source]A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. For consistency, always use """triple double quotes""" around docstrings.[20][21]
def function(parameter):
"""This docstring documents the function, describes the parameter requirements, etc."""
pass
print(function.__doc__)
Output:
This docstring documents the function, describes the parameter requirements, etc.
Recursion Example
[edit | edit source]The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.[22]
def factorial(value):
"""This function returns the factorial of the value provided using recursion."""
if type(value) is not int:
raise TypeError("Parameter value must be an integer.")
if value < 0:
result = 0
elif value == 0:
result = 1
else:
result = value * factorial(value - 1)
return result
print("5! =", factorial(5))
Output:
5! = 120
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- Review Python.org: Built-in Functions. Create a Python program that asks the user for a numeric input value. Demonstrate the use of a variety of built-in functions by displaying the input value's initial type (type). Then convert and display the input value as an integer (int), a float (float), and a Boolean (bool). Use the converted integer to display the value as a character (chr), and in binary (bin), octal (oct), and hexadecimal (hex) format. Use the converted float to display the value rounded to no decimal places (round), and formatted as currency with two decimal places (format). Include try and except to handle input errors. Test the program with both integer and floating point values.
- Create a Python program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a condition statement to determine their selection, and use functions to convert years to months, years to days, years to hours, and years to seconds. Display their approximate age in the selected timeframe. Include try and except to handle input errors.
- Review MathsIsFun: Conversion of Temperature. Create a Python program that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a condition statement to determine their selection and then gather the appropriate input. Use functions to convert Fahrenheit to Celsius and Celsius to Fahrenheit. Calculate and display the converted temperature. Include try and except to handle input errors.
- Review MathsIsFun: Area of Plane Shapes. Create a Python program that asks the user what shape they would like to calculate the area for. Use a condition statement to determine their selection and then gather the appropriate input. Use separate functions to calculate the area of each shape and then calculate and display the area of the selected shape. Include try and except to handle input errors.
- Review MathsIsFun: Greatest Common Factor. Create a Python program that asks the user to enter two integer values. Based on the recursive algorithm provided in Wikipedia: Recursion (computer science), use a recursive function to calculate the greatest common factor (greatest common divisor) of the two values and then display the result. Include try and except to handle input errors.
Lesson Summary
[edit | edit source]Function Concepts
[edit | edit source]- A function or subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.[23]
- In different programming languages, a function may be called a procedure, a subroutine, a routine, a method, or a subprogram.[24]
- A function is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other functions, and then branch back (return) to the next instruction after the call once the function's task is done.[25]
- The content of a function is its body, the piece of program code that is executed when the function is called or invoked.[26]
- A function may be written so that it expects to obtain one or more data values from the calling program (its parameters or formal parameters). The calling program provides actual values for these parameters, called arguments.[27]
- Function arguments may be passed using call-by-reference or call-by-value.[28]
- A function may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.[29]
- A function can be coded so that it may call itself recursively, at one or more places, to perform its task.[30]
- The advantages of breaking a program into functions include:[31]
- decomposing a complex programming task into simpler steps
- reducing duplicate code within a program
- enabling reuse of code across multiple programs
- hiding implementation details from users of the function
- With call by value, a parameter acts within the subroutine as a variable initialized to the value of the argument (a local (isolated) copy of the argument).[32]
- With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.[33]
- Some programming languages allow for a default argument to be explicitly or implicitly given in a subroutine's declaration.[34]
- Some languages allow functions to be defined to accept a variable number of arguments. For such languages, the functions must iterate through the list of arguments.[35]
- Some programming languages allow functions to have named parameters.[36]
Python Functions
[edit | edit source]- A Python function definition defines a user-defined function object. The basic syntax for declaring a function is:[37]
def <name>([parameters]):
<statements>
- Python arguments are passed using call by value.[38]
- By default, Python arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.[39]
- A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).[40]
- The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached.[41]
- Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.[42]
- The Python interpreter has a number of functions and types built into it that are always available.[43]
- A function definition defines a user-defined function object.[44] If specified, return leaves the current function call with the expression list (or None) as return value.[45]
- If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.[46]
- Variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.[47]
- The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.[48][49]
- A parameter is a named entity in a function definition that specifies an argument that the function can accept.[50] Functions may specify a default value for one or more arguments.[51] Functions may also be called using keyword arguments rather than positional arguments.[52]
- Errors should never pass silently.[53]
- Parameter validation is automated processing to validate the spelling or accuracy of parameters passed to a function or module.[54]
- An assertion is a statement that a true–false expression is expected to always be true at that point in the code.[55]
- The assert statement verifies that an expression is true or it raises an AssertionError. Unlike conditions, which are always executed, assert statements may be disabled when when optimization is requested (using command line option -O).[56]
- Functions may accept a variable number of arguments using the * operator.[57] The variable arguments are provided as a Python list.
- Variable named arguments may be accessed using the ** operator.[58][59][60] The variable named arguments are provided as a Python dictionary.
- A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. For consistency, always use """triple double quotes""" around docstrings.[61][62]
Key Terms
[edit | edit source]- algorithm
- A general process for solving a category of problems.[63]
- argument
- A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.[64]
- body
- The sequence of statements inside a function definition.[65]
- composition
- Using an expression as part of a larger expression, or a statement as part of a larger statement.[66]
- deterministic
- Pertaining to a program that does the same thing each time it runs, given the same inputs.[67]
- dot notation
- The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.[68]
- flow of execution
- The order in which statements are executed during a program run.[69]
- fruitful function
- A function that returns a value.[70]
- function
- A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.[71]
- function call
- A statement that executes a function. It consists of the function name followed by an argument list.[72]
- function definition
- A statement that creates a new function, specifying its name, parameters, and the statements it executes.[73]
- function object
- A value created by a function definition. The name of the function is a variable that refers to a function object.[74]
- header
- The first line of a function definition.[75]
- import statement
- A statement that reads a module file and creates a module object.[76]
- module object
- A value created by an import statement that provides access to the data and code defined in a module.[77]
- parameter
- A name used inside a function to refer to the value passed as an argument.[78]
- pseudorandom
- Pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program.[79]
- return value
- The result of a function. If a function call is used as an expression, the return value is the value of the expression.[80]
- void function
- A function that does not return a value.[81]
Review Questions
[edit | edit source]-
A function or subroutine is _____.A function or subroutine is a sequence of program instructions that perform a specific task, packaged as a unit.
-
In different programming languages, a function may be called a _____, a _____, a _____, a _____, or a _____.In different programming languages, a function may be called a procedure, a subroutine, a routine, a method, or a subprogram.
-
A function is often coded so that _____.A function is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other functions, and then branch back (return) to the next instruction after the call once the function's task is done.
-
The content of a function is _____.The content of a function is its body, the piece of program code that is executed when the function is called or invoked.
-
A function may be written so that it expects to obtain one or more data values from _____.A function may be written so that it expects to obtain one or more data values from the calling program (its parameters or formal parameters). The calling program provides actual values for these parameters, called arguments.
-
Function arguments may be passed using _____ or _____.Function arguments may be passed using call-by-reference or call-by-value.
-
A function may also return _____.A function may also return a computed value to its caller (its return value), or provide various result values or out(put) parameters.
-
A function can be coded so that it may call itself _____, at one or more places, to perform its task.A function can be coded so that it may call itself recursively, at one or more places, to perform its task.
-
The advantages of breaking a program into functions include:The advantages of breaking a program into functions include:
decomposing a complex programming task into simpler steps
reducing duplicate code within a program
enabling reuse of code across multiple programs
hiding implementation details from users of the function -
With call by value, a parameter acts within the subroutine as _____.With call by value, a parameter acts within the subroutine as a variable initialized to the value of the argument (a local (isolated) copy of the argument).
-
With call by reference, the argument supplied by the caller _____.With call by reference, the argument supplied by the caller can be affected by actions within the called subroutine.
-
Some programming languages allow for a default argument to be _____.Some programming languages allow for a default argument to be explicitly or implicitly given in a subroutine's declaration.
-
Some languages allow functions to be defined to accept a _____.Some languages allow functions to be defined to accept a variable number of arguments. For such languages, the functions must iterate through the list of arguments.
-
Some programming languages allow functions to have _____ parameters.Some programming languages allow functions to have named parameters.
-
A Python function definition defines a user-defined function object. The basic syntax for declaring a function is:A Python function definition defines a user-defined function object. The basic syntax for declaring a function is:
def <name>([parameters]):
<statements> -
Python arguments are passed using call by _____.Python arguments are passed using call by value.
-
By default, Python arguments are passed by _____.By default, Python arguments are passed by position. Parameter names may be used to identify parameters, bypassing position.
-
A recursive function definition has _____.A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).
-
The job of the recursive cases can be seen as _____.The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In a properly designed recursive function, with each recursive call, the input problem must be simplified in such a way that eventually the base case must be reached.
-
Recursive programming solutions include _____.Recursive programming solutions include mathematics calculations, data structure searches, and file system processing.
-
The Python interpreter has a number of functions and types _____.The Python interpreter has a number of functions and types built into it that are always available.
-
A function definition defines _____.A function definition defines a user-defined function object. If specified, return leaves the current function call with the expression list (or None) as return value.
-
If a variable is assigned a value anywhere within the function’s body, it’s assumed to be _____.If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
-
Variables that are only referenced inside a function are implicitly _____. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a _____.Variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
-
The nonlocal statement causes the listed identifiers to _____.The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
-
A parameter is _____.A parameter is a named entity in a function definition that specifies an argument that the function can accept. Functions may specify a default value for one or more arguments. Functions may also be called using keyword arguments rather than positional arguments.
-
Errors should _____.Errors should never pass silently.
-
Parameter validation is _____.Parameter validation is automated processing to validate the spelling or accuracy of parameters passed to a function or module.
-
An assertion is _____.An assertion is a statement that a true–false expression is expected to always be true at that point in the code.
-
The assert statement _____.The assert statement verifies that an expression is true or it raises an AssertionError. Unlike conditions, which are always executed, assert statements may be disabled when when optimization is requested (using command line option -O).
-
Functions may accept a variable number of arguments using _____.Functions may accept a variable number of arguments using the * operator. The variable arguments are provided as a Python list.
-
Variable named arguments may be accessed using _____.Variable named arguments may be accessed using the ** operator. The variable named arguments are provided as a Python dictionary.
-
A docstring is _____.A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. For consistency, always use """triple double quotes""" around docstrings.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Functions
- Quiz: Quizlet: Python Functions
See Also
[edit | edit source]- Python.org: More Control Flow Tools
- SoloLearn: Python
- DotNetPerls: Python global and nonlocal
- Python.org: Docstring Conventions
- Open Book Project: Python 3 - Functions
- Open Book Project: Python 3 - Fruitful Functions
- Python For Beginners: Functions
- DataCamp: Python Functions Tutorial
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Built-in Functions
- ↑ Python.org: Function definitions
- ↑ Python.org: The return statement
- ↑ Python.org: Rules for local and global variables
- ↑ Python.org: Rules for local and global variables
- ↑ Python.org: Nonlocal
- ↑ Python.org: Programming FAQ
- ↑ Python.org: Parameter
- ↑ Python.org: More flow control tools
- ↑ Python.org: More flow control tools
- ↑ Python.org: The Zen of Python
- ↑ Wikipedia: Parameter validation
- ↑ Wikipedia: Assertion (software development)
- ↑ Python.org: The assert statement
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ PythonTips: args and kwargs explained
- ↑ TutorialsPoint: Python Dictionary
- ↑ Python.org: Docstring Conventions
- ↑ Python.org: Documentation Strings
- ↑ Wikipedia: Factorial
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Subroutine
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Wikipedia: Parameter (computer programming)
- ↑ Python.org: Function definitions
- ↑ Python.org: Defining Functions
- ↑ Python.org: Keyword Arguments
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Recursion (computer science)
- ↑ Wikipedia: Recursion (computer science)
- ↑ Python.org: Built-in Functions
- ↑ Python.org: Function definitions
- ↑ Python.org: The return statement
- ↑ Python.org: Rules for local and global variables
- ↑ Python.org: Rules for local and global variables
- ↑ Python.org: Nonlocal
- ↑ Python.org: Programming FAQ
- ↑ Python.org: Parameter
- ↑ Python.org: More flow control tools
- ↑ Python.org: More flow control tools
- ↑ Python.org: The Zen of Python
- ↑ Wikipedia: Parameter validation
- ↑ Wikipedia: Assertion (software development)
- ↑ Python.org: The assert statement
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ PythonTips: args and kwargs explained
- ↑ TutorialsPoint: Python Dictionary
- ↑ Python.org: Docstring Conventions
- ↑ Python.org: Documentation Strings
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
- ↑ PythonLearn: Functions
Lesson 6 - Strings
[edit | edit source]This lesson introduces Python string processing.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:
- Standard Library
- String operations
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: Python for Informatics - Chapter 6 - Strings
- YouTube: Python - Strings
- YouTube: Python - String Slicing
- YouTube: Python - String Formatting
- YouTube: Python Strings Playlist
Examples
[edit | edit source]len() function
[edit | edit source]The len() function returns the length (the number of items) of an object.[1]
string = "Test"
print("len(string):", len(string))
Output:
len(string): 4
Strings
[edit | edit source]Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.[2]
string = "Test"
print("Characters:")
for letter in string:
print(letter)
print("\nCharacters by position:")
for i in range(len(string)):
print("string[%d]: %c" % (i, string[i]))
Output:
Characters: T e s t Characters by position: string[0]: T string[1]: e string[2]: s string[3]: t
Membership Comparisons
[edit | edit source]The operators in
and not in
test for membership. x in s
evaluates to true if x is a member of s, and false otherwise.[3]
alphabet = "abcdefghijklmnopqrstuvwxyz"
string = "Python Programming/Strings"
print("The string contains:")
for letter in alphabet:
if letter in string.lower():
print(letter)
Output:
The string contains: a g h i m n o p r s t y
String Methods
[edit | edit source]Strings implement all of the common sequence operations, along with additional methods such as case validation and conversion.[4]
string = "Test"
print("string:", string)
print("string.isalpha():", string.isalpha())
print("string.islower():", string.islower())
print("string.isnumeric():", string.isnumeric())
print("string.isspace():", string.isspace())
print("string.istitle():", string.istitle())
print("string.isupper():", string.isupper())
print("string.lower():", string.lower())
print("string.strip():", string.strip())
print("string.swapcase():", string.swapcase())
print("string.title():", string.title())
print("string.upper():", string.upper())
Output:
string: Test string.isalpha(): True string.islower(): False string.isnumeric(): False string.isspace(): False string.istitle(): True string.isupper(): False string.lower(): test string.strip(): Test string.swapcase(): tEST string.title(): Test string.upper(): TEST
String Parsing
[edit | edit source]Python substrings are referred to as slices. Slices are accessed using the syntax string[start:end]
, with the first character index starting at zero. The slice will include the characters from start up to but not including end. If end is omitted, the slice will include the characters from start through the end of the string. String slices may use negative indexing, in which case the index counts backwards from the end of the string.[5] The find() method returns the lowest index in the string where a substring is found within the given slice. Returns -1 if the substring is not found.[6]
string = "Python Programming/Strings"
index = string.find("/")
if index >= 0:
project = string[0:index]
page = string[index + 1:]
print("Project:", project)
print("Page:", page)
Output:
Project: Python Programming Page: Strings
String Formatting
[edit | edit source]String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values.[7]
print("Value:", value)
print("Integer: %i" % value)
print("Octal: %o" % value)
print("Hexadecimal: %x" % value)
print("Float: %.2f" % value)
print("Exponent: %.2e" % value)
print("Character: %c" % value)
print("String: %s" % value)
print("Multiple: %i, %o, %x, %.2f, %.2e, %c, %s" %
(value, value, value, value, value, value, value))
Output:
Value: 65.5 Integer: 65 Octal: 101 Hexadecimal: 41 Float: 65.50 Exponent: 6.55e+01 Character: A String: 65.5 Multiple: 65, 101, 41, 65.50, 6.55e+01, A, 65.5
str.format() Method
[edit | edit source]The str.format() method uses format strings that contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output.[8]
integer = 65
float = 65.5
string = "65.5"
print("Decimal: {:d}".format(integer))
print("Binary: {:b}".format(integer))
print("Octal: {:o}".format(integer))
print("Hexadecimal: {:x}".format(integer))
print("Character: {:c}".format(integer))
print("Float: {:.2f}".format(float))
print("Exponent: {:.2e}".format(float))
print("String: {:s}".format(string))
print("Multiple: {:d}, {:b}, {:o}, {:x}, {:c}, {:.2f}, {:.2e}, {:s}".format(
integer, integer, integer, integer, integer, float, float, string))
Output:
Decimal: 65 Binary: 1000001 Octal: 101 Hexadecimal: 41 Character: A Float: 65.50 Exponent: 6.55e+01 String: 65.5 Multiple: 65, 1000001, 101, 41, A, 65.50, 6.55e+01, 65.5
String Interpolation
[edit | edit source]Introduced in Python 3.6, string interpolation formats strings that contain “replacement fields” surrounded by curly braces {}, similar to the str.format() method.[9] However, an uppercase or lowercase 'f' is placed before the string to indicate string formatting:
integer = 65
float = 65.5
string = "65.5"
print(f"Decimal: {integer:d}")
print(f"Binary: {integer:b}")
print(f"Octal: {integer:o}")
print(f"Hexadecimal: {integer:x}")
print(f"Character: {integer:c}")
print(f"Float: {float:.2f}")
print(f"Exponent: {float:.2e}")
print(f"String: {string:s}")
print(f"Multiple: {integer:d}, {integer:b}, {integer:o}, {integer:x}, {integer:c}, {float:.2f}, {float:.2e}, {string:s}")
Output:
Decimal: 65
Binary: 1000001
Octal: 101
Hexadecimal: 41
Character: A
Float: 65.50
Exponent: 6.55e+01
String: 65.5
Multiple: 65, 1000001, 101, 41, A, 65.50, 6.55e+01, 65.5
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- Review Python.org: String methods. Create a Python program that asks the user for a line of text containing a first name and last name. Use string methods to parse the line and print out the name in the form last name, first initial, such as
Lastname, F.
Include a trailing period after the first initial. Ensure that the first letter of each name part is capitalized, and the rest of the last name is lower case. Include error handling in case the user does not enter exactly two name parts. Use a user-defined function for the actual string processing, separate from input and output. - Review Python.org: String methods. Create a Python program that asks the user for a line of comma-separated-values. It could be a sequence of test scores, names, or any other values. Use string methods to parse the line and print out each item on a separate line. Remove commas and any leading or trailing spaces from each item when printed. If the item is numeric, display it formatted as a floating point value with two decimal places. If the value is not numeric, display it as is.
- Review Python.org: String methods. Create a Python program that asks the user for a line of text that contains HTML tags, such as:
<p><strong>This is a bold paragraph.</strong></p>
Use string methods to search for and remove all HTML tags, and then print the remaining untagged text. Include error handling in case an HTML tag isn't entered correctly (an unmatched < or >). Use a user-defined function for the actual string processing, separate from input and output. - Review Python.org: String methods. Create a Python program that asks the user for a line of text. Then ask the user for the number of characters to print in each line, the number of lines to be printed, and a scroll direction, right or left. Using the given line of text, duplicate the text as needed to fill the given number of characters per line. Then print the requested number of lines, shifting the entire line's content by one character, left or right, each time the line is printed. The first or last character will be shifted / appended to the other end of the string. For example:
Repeat this. Repeat this.
epeat this. Repeat this. R
peat this. Repeat this. Re
Lesson Summary
[edit | edit source]- A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable.[10]
- A string variable may allow its elements to be mutated and the length changed, or it may be fixed (after creation).[11]
- Python strings are immutable — they cannot be changed.[12]
- The len() function returns the length (the number of items) of an object.[13]
- Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.[14]
- The operators
in
andnot in
test for membership.x in s
evaluates to true if x is a member of s, and false otherwise.[15] - String methods include: isalpha(), islower(), isnumeric(), isspace(), istitle(), isupper(), lower(), strip(), swapcase(), title(), and upper().[16]
- Python substrings are referred to as slices. Slices are accessed using the syntax
string[start:end]
, with the first character index starting at zero. The slice will include the characters from start up to but not including end. If end is omitted, the slice will include the characters from start through the end of the string.[17] - String slices may use negative indexing, in which case the index counts backwards from the end of the string.[18]
- The find() method returns the lowest index in the string where a substring is found within the given slice. Returns -1 if the substring is not found.[19]
- String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given
format % values
(where format is a string), % conversion specifications in format are replaced with zero or more elements of values.[20] - The str.format() method uses format strings that contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output.[21]
Key Terms
[edit | edit source]- counter
- A variable used to count something, usually initialized to zero and then incremented.[22]
- empty string
- A string with no characters and length 0, represented by two quotation marks.[23]
- format operator
- An operator, %, that takes a format string and a tuple and generates a string that includes the elements of the tuple formatted as specified by the format string.[24]
- format sequence
- A sequence of characters in a format string, like %d, that specifies how a value should be formatted.[25]
- format string
- A string, used with the format operator, that contains format sequences.[26]
- flag
- A boolean variable used to indicate whether a condition is true.[27]
- invocation
- A statement that calls a method.[28]
- immutable
- The property of a sequence whose items cannot be assigned.[29]
- index
- An integer value used to select an item in a sequence, such as a character in a string.[30]
- item
- One of the values in a sequence.[31]
- method
- A function that is associated with an object and called using dot notation.[32]
- object
- Something a variable can refer to. For now, you can use “object” and “value” interchangeably.[33]
- search
- A pattern of traversal that stops when it finds what it is looking for.[34]
- sequence
- An ordered set; that is, a set of values where each value is identified by an integer index.[35]
- slice
- A part of a string specified by a range of indices.[36]
- traverse
- To iterate through the items in a sequence, performing a similar operation on each.[37]
Review Questions
[edit | edit source]-
A string is _____.A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable.
-
A string variable may _____.A string variable may allow its elements to be mutated and the length changed, or it may be fixed (after creation).
-
Python strings are _____ — they cannot be changed.Python strings are immutable — they cannot be changed.
-
The len() function returns _____.The len() function returns the length (the number of items) of an object.
-
Textual data in Python is handled with _____.Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.
-
The operators _____ and _____ test for membership. x _____ s evaluates to true if x is a member of s, and false otherwise.The operators in and not in test for membership. x in s evaluates to true if x is a member of s, and false otherwise.
-
String methods include:String methods include: isalpha(), islower(), isnumeric(), isspace(), istitle(), isupper(), lower(), strip(), swapcase(), title(), and upper().
-
Python substrings are referred to as _____.Python substrings are referred to as slices.
-
Slices are accessed using the syntax _____.Slices are accessed using the syntax string[start:end].
-
The first character index in a slice starts at _____. The slice will include _____. If end is omitted, the slice will include _____.The first character index in a slice starts at zero. The slice will include the characters from start up to but not including end. If end is omitted, the slice will include the characters from start through the end of the string.
-
String slices may use negative indexing, in which case _____.String slices may use negative indexing, in which case the index counts backwards from the end of the string.
-
The find() method returns _____.The find() method returns the lowest index in the string where a substring is found within the given slice, and returns -1 if the substring is not found.
-
String objects have one unique built-in operation: the % operator (modulo). This is also known as _____.String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values.
-
The str.format() method uses format strings that contain “replacement fields” surrounded by _____.The str.format() method uses format strings that contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Strings
- Quiz: Quizlet: Python Strings
See Also
[edit | edit source]- Python.org: An Informal Introduction to Python
- PythonBasics: Strings and exercises
- SoloLearn: Python
- Open Book Project: Python 3 - Strings
- Google Developers: Python Strings
- Learn Python: Basic String Operations
- PythonForBeginners: String Manipulation
- W3Schools: Python String Methods
- Real Python: Python String Formatting
References
[edit | edit source]- ↑ Python.org Built-in Functions
- ↑ Python.org: Built-in Types
- ↑ Python.org: Expressions
- ↑ Python.org: Built-in Types
- ↑ Python.org: Strings
- ↑ Python.org: Built-in Types
- ↑ Python.org: printf-style String Formatting
- ↑ Python.org: Format String Syntax
- ↑ Python, Real. "Python 3's f-Strings: An Improved String Formatting Syntax (Guide) – Real Python". realpython.com. Retrieved 2019-02-22.
- ↑ Wikipedia: String (computer science)
- ↑ Wikipedia: String (computer science)
- ↑ Python.org: Strings
- ↑ Python.org Built-in Functions
- ↑ Python.org: Built-in Types
- ↑ Python.org: Expressions
- ↑ Python.org: Built-in Types
- ↑ Python.org: Strings
- ↑ Python.org: Strings
- ↑ Python.org: Built-in Types
- ↑ Python.org: printf-style String Formatting
- ↑ Python.org: Format String Syntax
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
- ↑ PythonLearn: Strings
Lesson 7 - Lists
[edit | edit source]This lesson introduces Python lists.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Data Structures
- List
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: Python for Informatics - Chapter 8 - Lists
- YouTube: Python Lists
- YouTube: Immutable vs Mutable Objects in Python
Examples
[edit | edit source]Lists
[edit | edit source]Python supports a number of compound data types used to group other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.[2]
list = [1, 2, 3]
for item in list:
print(item)
Output:
1 2 3
Index
[edit | edit source]List items can be accessed by index.[3]
list = [1, 2, 3]
for i in range(len(list)):
print("list[%d]: %d" % (i, list[i]))
Output:
list[0]: 1 list[1]: 2 list[2]: 3
Concatenation
[edit | edit source]Lists support concatenation.[4]
list = [1, 2, 3]
list += [4, 5]
for i in range(len(list)):
print("list[%d]: %d" % (i, list[i]))
Output:
list[0]: 1 list[1]: 2 list[2]: 3 list[3]: 4 list[4]: 5
Slicing
[edit | edit source]Lists may be sliced.[5]
list = [1, 2, 3, 4, 5]
list = list[0:2] + list[3:]
for i in range(len(list)):
print("list[%d]: %d" % (i, list[i]))
Output:
list[0]: 1 list[1]: 2 list[2]: 4 list[3]: 5
Mutable
[edit | edit source]List items are mutable, i.e. it is possible to change their content.[6]
list = [1, 2, 3]
for i in range(len(list)):
list[i] = -list[i]
print("list[%d]: %d" % (i, list[i]))
Output:
list[0]: -1 list[1]: -2 list[2]: -3
Multidimensional
[edit | edit source]Multi dimensional lists are lists within lists.[7]
table = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in range(len(table)):
for column in range(len(table[row])):
print(table[row][column], end = '\t')
print()
Output:
1 2 3 4 5 6 7 8 9
Methods
[edit | edit source]Lists support a variety of methods, including:[8]
- list.append(x) - Adds an item to the end of the list.
- list.insert(i, x) - Inserts an item at a given position.
- list.remove(x) - Removes the first item from the list whose value is x
- list.reverse() - Reverse the elements of the list in place.
- list.sort() - Sorts the items of the list in place.
- list.clear() - Removes all items from the list.
list = []
print("List:", list)
list.append(1)
list.append(2)
print("After append:", list)
list.insert(2, 3)
list.insert(0, 4)
print("After insert:", list)
list.remove(4)
print("After remove:", list)
list.reverse()
print("After reverse:", list)
list.sort()
print("After sort:", list)
list.clear()
print("After clear:", list)
Output:
List: [] After append: [1, 2] After insert: [4, 1, 2, 3] After remove: [1, 2, 3] After reverse: [3, 2, 1] After sort: [1, 2, 3] After clear: []
Stacks and Queues
[edit | edit source]The list.pop([i]) method removes the item at the given position in the list, and returns it. If no index is specified, pop() removes and returns the last item in the list.[9] This allows for simple stack (last-in, first-out) and queue (first-in, first-out) processing.
print("Stack: Last in, first out")
list = []
list.append(1)
list.append(2)
list.append(3)
while len(list) > 0:
print(list.pop())
print("\nQueue: First in, first out")
list = []
list.append(1)
list.append(2)
list.append(3)
while len(list) > 0:
print(list.pop(0))
Output:
Stack: Last in, first out 3 2 1 Queue: First in, first out 1 2 3
Split
[edit | edit source]The string split(<separator>) method returns a list of the words in the string, using separator as the delimiter string. If separator is not specified, runs of consecutive whitespace are regarded as a single separator.[10]
string = "This is a test"
list = string.split()
print(list)
string = "So-is-this"
list = string.split("-")
print(list)
Output:
['This', 'is', 'a', 'test'] ['So', 'is', 'this']
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- Create a Python program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a list. Finally, display the list of entered scores sorted in descending order and then calculate and display the high, low, and average for the entered scores. Include try and except to handle input errors.
- Create a Python program that asks the user to enter a line of comma-separated grade scores. Use the string split() method to parse the line and display the list of entered scores sorted in descending order and then calculate and display the high, low, and average for the entered scores. Include try and except to handle input errors.
- Create a Python program that asks the user to enter a line of text. Use the string split() method to parse the line and then display the list of words in alphabetical order with any duplicate words removed from the list.
- Create a Python program that asks the user for a line of text that contains HTML tags, such as:
<p><strong>This is a bold paragraph.</strong></p>
Use string methods to search for and remove all HTML tags from the text, saving each removed tag in a list. Print the untagged text and then display the list of removed tags sorted in alphabetical order with duplicate tags removed. Include error handling in case an HTML tag isn't entered correctly (an unmatched < or >). Use a user-defined function for the actual string processing, separate from input and output.
Lesson Summary
[edit | edit source]List Concepts
[edit | edit source]- A list or sequence is a data type that represents an ordered sequence of values, where the same value may occur more than once.[11]
- Lists are a basic example of containers, as they contain other values. If the same value occurs multiple times, each occurrence is considered a distinct item.[12]
- A list can often be constructed by writing the items in sequence, separated by commas, semicolons, or spaces, within a pair of delimiters such as parentheses '()', brackets '[]', braces '{}', or angle brackets '<>'. [13]
- Some languages may allow list types to be indexed or sliced like array types, in which case the data type is more accurately described as an array.[14]
- An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.[15]
- Lists can be used to store a list of elements. However, unlike in traditional arrays, lists can expand and shrink, and are stored dynamically in memory.[16]
Python Lists
[edit | edit source]- Python lists can be written as a list of comma-separated values (items) between square brackets.[17]
- Lists might contain items of different types, but usually the items all have the same type.[18]
- List items can be accessed by index using the syntax list[index].[19]
- Lists support concatenation using the syntax list + list.[20]
- Lists may be sliced using the syntax list[start:end]. The slice will include the starting index value up to but not including the ending index value.[21]
- List items are mutable, i.e. it is possible to change their content.[22]
- Multidimensional lists are lists within lists, accessed using the syntax list[index][index].[23]
- list.append(x) - adds an item to the end of the list.[24]
- list.insert(i, x) - Inserts an item at a given position.[25]
- list.remove(x) - Removes the first item from the list whose value is x.[26]
- list.reverse() - Reverse the elements of the list in place.[27]
- list.sort() - Sorts the items of the list in place.[28]
- list.clear() - Removes all items from the list.[29]
- list.pop([i]) removes the item at the given position in the list, and returns it. If no index is specified, pop() removes and returns the last item in the list.[30]
- string.split(<separator>) returns a list of the words in the string, using separator as the delimiter string. If separator is not specified, runs of consecutive whitespace are regarded as a single separator.[31]
Key Terms
[edit | edit source]- aliasing
- A circumstance where two or more variables refer to the same object.[32]
- delimiter
- A character or string used to indicate where a string should be split.[33]
- element
- One of the values in a list (or other sequence); also called items.[34]
- equivalent
- Having the same value.[35]
- index
- An integer value that indicates an element in a list.[36]
- identical
- Being the same object (which implies equivalence).[37]
- list
- A sequence of values.[38]
- list traversal
- The sequential accessing of each element in a list.[39]
- nested list
- A list that is an element of another list.[40]
- object
- Something a variable can refer to. An object has a type and a value.[41]
- queue
- A data structure in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the end of the collection and removal of entities from the start of the collection (first-in, first-out).[42]
- reference
- The association between a variable and its value.[43]
- stack
- A data structure in which the entities in the collection are kept in order and the principal (or only) operations on the collection are push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed (last-in, first-out).[44]
Review Questions
[edit | edit source]-
A list or sequence is _____.A list or sequence is a data type that represents an ordered sequence of values, where the same value may occur more than once.
-
Lists are a basic example of _____. If the same value occurs multiple times, _____.Lists are a basic example of containers, as they contain other values. If the same value occurs multiple times, each occurrence is considered a distinct item.
-
A list can often be constructed by _____.A list can often be constructed by writing the items in sequence, separated by commas, semicolons, or spaces, within a pair of delimiters such as parentheses '()', brackets '[]', braces '{}', or angle brackets '<>'.
-
Some languages may allow list types to be _____ like array types, in which case the data type is more accurately described as an array.Some languages may allow list types to be indexed or sliced like array types, in which case the data type is more accurately described as an array.
-
An array is _____.An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.
-
Lists can be used to store a list of elements. However, unlike in traditional arrays, lists can _____, and are stored _____.Lists can be used to store a list of elements. However, unlike in traditional arrays, lists can expand and shrink, and are stored dynamically in memory.
-
Python lists can be written as _____.Python lists can be written as a list of comma-separated values (items) between square brackets.
-
Lists might contain _____.Lists might contain items of different types, but usually the items all have the same type.
-
List items can be accessed by index using the syntax _____.List items can be accessed by index using the syntax list[index].
-
Lists support concatenation using the syntax _____.Lists support concatenation using the syntax list + list.
-
Lists may be sliced using the syntax _____.Lists may be sliced using the syntax list[start:end]. The slice will include the starting index value up to but not including the ending index value.
-
List items are mutable, i.e. _____.List items are mutable, i.e. it is possible to change their content.
-
Multidimensional lists are _____.Multidimensional lists are lists within lists, accessed using the syntax list[index][index].
-
list.append(x) - _____.list.append(x) - Adds an item to the end of the list.
-
list.insert(i, x) - _____.list.insert(i, x) - Inserts an item at a given position.
-
list.remove(x) - _____.list.remove(x) - Removes the first item from the list whose value is x.
-
list.reverse() - _____.list.reverse() - Reverse the elements of the list in place.
-
list.sort() - _____.list.sort() - Sorts the items of the list in place.
-
list.clear() - _____.list.clear() - Removes all items from the list.
-
list.pop() - _____.list.pop() - Removes the item at the given position in the list, and returns it. If no index is specified, pop() removes and returns the last item in the list.
-
string.split() - _____.string.split() - Returns a list of the words in the string, using separator as the delimiter string. If separator is not specified, runs of consecutive whitespace are regarded as a single separator.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Lists
- Flashcards: Quizlet: Python List Methods
- Flashcards: Quizlet: Python List Operations
- Quiz: Quizlet: Python Lists
- Quiz: Quizlet: Python List Methods
- Quiz: Quizlet: Python List Operations
See Also
[edit | edit source]- Python.org: Data Structures
- PythonBasics: lists
- SoloLearn: Python
- Open Book Project: Python 3 - Lists
- This Pointer: Sorting Numerical Arrays in Ascending or Descending Order
- Python Arrays
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ PythonProgramming.net: Multi-dimensional lists
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Split
- ↑ Wikipedia: List (abstract data type)
- ↑ Wikipedia: List (abstract data type)
- ↑ Wikipedia: List (abstract data type)
- ↑ Wikipedia: List (abstract data type)
- ↑ Wikipedia: Array
- ↑ Wikipedia: List (abstract data type)
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ PythonProgramming.net: Multi-dimensional lists
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Split
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ Wikipedia: Queue (abstract data type)
- ↑ PythonLearn: Lists
- ↑ Wikipedia: Queue (abstract data type)
Lesson 8 - Dictionaries
[edit | edit source]This lesson introduces Python dictionaries.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Data Structures
- Dictionary
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: Python for Informatics - Chapter 9 - Dictionaries
- YouTube: Python Dictionary
- YouTube: Python - Min, Max, and Sorting Dictionaries
- YouTube: Python Dictionaries Playlist
Examples
[edit | edit source]Dictionaries
[edit | edit source]Dictionaries are collections that are indexed by keys, which can be any immutable type. It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). Placing a comma-separated list of key:value pairs within braces adds initial key:value pairs to the dictionary.[2]
dictionary = {
'cat': 'Frisky',
'dog': 'Spot',
'fish': 'Bubbles',
}
print("dictionary:", dictionary)
print("dictionary['cat']:", dictionary['cat'])
print("dictionary['dog']:", dictionary['dog'])
print("dictionary['fish']:", dictionary['fish'])
Output:
dictionary: {'dog': 'Spot', 'fish': 'Bubbles', 'cat': 'Frisky'} dictionary['cat']: Frisky dictionary['dog']: Spot dictionary['fish']: Bubbles
Dictionary Updates
[edit | edit source]A pair of braces creates an empty dictionary: {}. Dictionary items may be added, updated, and deleted by key.[3]
dictionary = {}
dictionary['cat'] = 'Frisky'
dictionary['dog'] = 'Spot'
dictionary['fish'] = 'Bubbles'
print("dictionary:", dictionary)
dictionary['dog'] = 'Rover'
print("dictionary:", dictionary)
del dictionary['fish']
print("dictionary:", dictionary)
Output:
dictionary: {'cat': 'Frisky', 'fish': 'Bubbles', 'dog': 'Spot'} dictionary: {'cat': 'Frisky', 'fish': 'Bubbles', 'dog': 'Rover'} dictionary: {'cat': 'Frisky', 'dog': 'Rover'}
Multidimensional Dictionaries
[edit | edit source]Dictionaries may be nested.
dictionary = {
'John': {'name': 'John Smith', 'phone': '123-555-0101'},
'Jose': {'name': 'Jose Garcia', 'phone': '123-555-0102'}
}
print("John's name:", dictionary['John']['name'])
print("Jose's phone:",dictionary['Jose']['phone'])
Output:
John's name: John Smith Jose's phone: 123-555-0102
Looping
[edit | edit source]Dictionary items may be accessed with a for loop.
dictionary = {
'cat': 'Frisky',
'dog': 'Spot',
'fish': 'Bubbles',
}
for key in dictionary:
print("dictionary[%s]: %s" % (key, dictionary[key]))
Output:
dictionary[dog]: Spot dictionary[fish]: Bubbles dictionary[cat]: Frisky
Sorting by Key
[edit | edit source]Dictionaries are unordered. Dictionary items may be displayed in key order by sorting a list of keys using the sorted() function and the dictionary.keys() method.[4]
dictionary = {
'cat': 'Frisky',
'dog': 'Spot',
'fish': 'Bubbles',
}
for key in sorted(dictionary.keys()):
print("dictionary[%s]: %s" % (key, dictionary[key]))
Output:
dictionary[cat]: Frisky dictionary[dog]: Spot dictionary[fish]: Bubbles
Sorting by Value
[edit | edit source]Dictionaries are unordered. Dictionary items may be displayed in value order by sorting a list of key-value pairs using the sorted() function and the dictionary.get() method.[5]
dictionary = {
'cat': 'Frisky',
'dog': 'Spot',
'fish': 'Bubbles',
}
for key in sorted(dictionary, key=dictionary.get):
print("dictionary[%s]: %s" % (key, dictionary[key]))
Output:
dictionary[fish]: Bubbles dictionary[cat]: Frisky dictionary[dog]: Spot
Dictionary as Return Value
[edit | edit source]Functions may return multiple values using a dictionary.[6]
def function(x, y):
...
return {'x': x, 'y': y}
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- Create a Python program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a dictionary, counting how many times each score is entered. Finally, use a function to display the dictionary of entered scores sorted in descending order and a histogram showing how many times each score was entered. Include try and except to handle input errors. For example:
100: *
90: ***
80: *****
70: **
- Create a Python program that asks the user to enter a line of comma-separated grade scores. Use the string split() method to parse the line and add each score to a dictionary, counting how many times each score is entered. Finally, use a function to display the list of entered scores sorted in descending order and a histogram showing how many times each score was entered. Include try and except to handle input errors. For example:
100: *
90: ***
80: *****
70: **
- Create a Python program that asks the user to enter a line of text. Use the string split() method to parse the line and add each word to a dictionary, counting how many times each word is entered. Convert words to lower case and remove any punctuation to prevent duplicate or invalid results. Finally, use a function to display the list of entered words sorted in alphabetical order and a histogram showing how many times each word was entered. Include try and except to handle input errors. For example:
cat: *
hat: *
in: *
the: **
- Create a Python program that asks the user for a line of text that contains HTML tags, such as:
<p><strong>This is a bold paragraph.</strong></p>
Use string methods to search for and remove all HTML tags from the text, saving each removed tag in a dictionary. Print the untagged text and then use a function to display the list of removed tags sorted in alphabetical order and a histogram showing how many times each tag was used. Include error handling in case an HTML tag isn't entered correctly (an unmatched < or >). Use a user-defined function for the actual string processing, separate from input and output. For example:
</p>: *
</strong>: *
<p>: *
<strong>: *
Lesson Summary
[edit | edit source]Dictionary Concepts
[edit | edit source]- A dictionary or associative array is a data type composed of a collection of (key: value) pairs, such that each possible key appears at most once in the collection.[7]
- Dictionary operations include:[8]
- the addition of a pair to the collection
- the removal of a pair from the collection
- the modification of an existing pair
- the lookup of a value associated with a particular key
- Dictionaries are typically implemented in programming languages as either a hash table or a search tree.[9]
- A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.[10]
- A hash function is any function that can be used to map data of arbitrary size to data of fixed size.[11]
- A good hash function should map the expected inputs as evenly as possible over its output range.[12]
Python Dictionaries
[edit | edit source]- Dictionaries are collections that are indexed by keys, which can be any immutable type.[13]
- It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).[14]
- Placing a comma-separated list of key:value pairs within braces adds initial key:value pairs to the dictionary using the syntax
dictionary = {key: value, key: value}
.[15] - A pair of braces creates an empty dictionary: {}. Dictionary items may be added, updated, and deleted by key using the syntax
dictionary[key] = value
anddel dictionary[key]
.[16] - Dictionaries may be nested and are accessed using the syntax
dictionary[key][subkey]
- Dictionary items may be accessed with a
for
loop. - Dictionaries are unordered. Dictionary items may be displayed in key order by sorting a list of keys using the
sorted()
function and thedictionary.keys()
method.[17] - Dictionaries are unordered. Dictionary items may be displayed in value order by sorting a list of key-value pairs using the
sorted()
function and thedictionary.get()
method.[18]
Key Terms
[edit | edit source]- dictionary
- A mapping from a set of keys to their corresponding values.[19]
- hashtable
- The algorithm used to implement Python dictionaries.[20]
- hash function
- A function used by a hashtable to compute the location for a key.[21]
- histogram
- A set of counters.[22]
- implementation
- A way of performing a computation.[23]
- item
- Another name for a key-value pair.[24]
- key
- An object that appears in a dictionary as the first part of a key-value pair.[25]
- key-value pair
- The representation of the mapping from a key to a value.[26]
- lookup
- A dictionary operation that takes a key and finds the corresponding value.[27]
- nested loops
- When there are one or more loops “inside” of another loop. The inner loop runs to completion each time the outer loop runs once.[28]
- value
- An object that appears in a dictionary as the second part of a key-value pair. This is more specific than our previous use of the word “value”.[29]
Review Questions
[edit | edit source]-
A dictionary or associative array is _____.A dictionary or associative array is a data type composed of a collection of (key: value) pairs, such that each possible key appears at most once in the collection.
-
Dictionary operations include:Dictionary operations include:
the addition of a pair to the collection
the removal of a pair from the collection
the modification of an existing pair
the lookup of a value associated with a particular key -
Dictionaries are typically implemented in programming languages as _____.Dictionaries are typically implemented in programming languages as either a hash table or a search tree.
-
A hash table uses _____.A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.
-
A hash function is _____.A hash function is any function that can be used to map data of arbitrary size to data of fixed size.
-
A good hash function should _____.A good hash function should map the expected inputs as evenly as possible over its output range.
-
Python dictionaries are _____.Python dictionaries are collections that are indexed by keys, which can be any immutable type.
-
It is best to think of a dictionary as _____.It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
-
Placing a comma-separated list of key:value pairs within braces adds initial key:value pairs to the dictionary using the syntax _____.{{{2}}}
-
A pair of braces creates an empty dictionary: {}. Dictionary items may be added, updated, and deleted by key using the syntax _____.{{{2}}}
-
Dictionaries may be nested and are accessed using the syntax _____Dictionaries may be nested and are accessed using the syntax dictionary[key][subkey]
-
Dictionary items may be accessed with a _____ loop.Dictionary items may be accessed with a for loop.
-
Dictionaries are unordered. Dictionary items may be displayed in key order by _____.Dictionaries are unordered. Dictionary items may be displayed in key order by sorting a list of keys using the sorted() function and the dictionary.keys()method.
-
Dictionaries are unordered. Dictionary items may be displayed in value order by _____.Dictionaries are unordered. Dictionary items may be displayed in value order by sorting a list of key-value pairs using the sorted() function and the dictionary.get() method.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Dictionaries
- Flashcards: Quizlet: Python Dictionary Methods
- Quiz: Quizlet: Python Dictionaries
- Quiz: Quizlet: Python Dictionary Methods
See Also
[edit | edit source]- Python.org: Data Structures
- SoloLearn: Python
- Open Book Project: Python 3 - Dictionaries
- Dictionaries in Python
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Dictionaries
- ↑ Python.org: Dictionaries
- ↑ Python.org: Dictionaries
- ↑ Python.org: Dictionaries
- ↑ Hitchhiker's Guide to Python: Code Style
- ↑ Wikipedia: Associative array
- ↑ Wikipedia: Associative array
- ↑ Wikipedia: Associative array
- ↑ Wikipedia: Hash table
- ↑ Wikipedia: Hash function
- ↑ Wikipedia: Hash function
- ↑ Python.org: Dictionaries
- ↑ Python.org: Dictionaries
- ↑ Python.org: Dictionaries
- ↑ Python.org: Dictionaries
- ↑ Python.org: Dictionaries
- ↑ Python.org: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
- ↑ PythonLearn: Dictionaries
Lesson 9 - Tuples and Sets
[edit | edit source]This lesson introduces Python tuples and sets by comparing them to lists and dictionaries.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Data Structures
- Tuple
- Sequences
- Set
Readings
[edit | edit source]Multimedia
[edit | edit source]Examples
[edit | edit source]Data Structures
[edit | edit source]Python data structures include lists, dictionaries, tuples, and sets.[2]
list = [1, 2, 3]
dictionary = {1: "one", 2: "two", 3: "three"}
tuple = (1, 2, 3)
set = {1, 2, 3}
print("list:", list)
print("dictionary:", dictionary)
print("tuple:", tuple)
print("set:", set)
Output:
list: [1, 2, 3] dictionary: {1: 'one', 2: 'two', 3: 'three'} tuple: (1, 2, 3) set: {1, 2, 3}
Data Types
[edit | edit source]The data types for a list, dictionary, tuple, and set, are 'list', 'dict', 'tuple', and 'set', respectively.[3]
list = [1, 2, 3]
dictionary = {1: "one", 2: "two", 3: "three"}
tuple = (1, 2, 3)
set = {1, 2, 3}
print("list:", type(list))
print("dictionary:", type(dictionary))
print("tuple:", type(tuple))
print("set:", type(set))
Output:
list: <class 'list'> dictionary: <class 'dict'> tuple: <class 'tuple'> set: <class 'set'>
Functions
[edit | edit source]The list(), dict(), tuple(), and set() functions may be used to create list, dictionary, tuple, and set objects, respectively.[4]
print(list((1, 2, 3)))
print(dict(one = 1, two = 2, three = 3))
print(tuple((1, 2, 3)))
print(set((1, 2, 3)))
Output:
[1, 2, 3] {'three': 3, 'two': 2, 'one': 1} (1, 2, 3) {1, 2, 3}
Mutability
[edit | edit source]List, dictionary and set items are mutable. Tuple items are immutable.[5]
list = [1, 2, 3]
dictionary = {1: "one", 2: "two", 3: "three"}
tuple = (1, 2, 3)
set = {1, 2, 3}
list[0] = 0
print("list: mutable")
dictionary[1] = "zero"
print("dictionary: mutable")
try:
tuple[0] = 0
print("tuple: mutable")
except:
print("tuple: immutable")
try:
set |= {0}
print("set: mutable")
except:
print("set: immutable")
print()
print("list:", list)
print("dictionary:", dictionary)
print("tuple:", tuple)
print("set:", set)
Output:
list: mutable dictionary: mutable tuple: immutable set: mutable list: [0, 2, 3] dictionary: {1: 'zero', 2: 'two', 3: 'three'} tuple: (1, 2, 3) set: {0, 1, 2, 3}
Order
[edit | edit source]Lists and tuples maintain order. Dictionaries and sets are unordered.[6]
list = ["fish", "dog", "cat"]
tuple = ("fish", "dog", "cat")
dictionary = {
'fish': 'Bubbles',
'dog': 'Spot',
'cat': 'Frisky',
}
set = {"fish", "dog", "cat"}
print("list:", list)
print("dictionary:", dictionary)
print("tuple:", tuple)
print("set:", set)
Output:
list: ['fish', 'dog', 'cat'] tuple: ('fish', 'dog', 'cat') dictionary: {'dog': 'Spot', 'fish': 'Bubbles', 'cat': 'Frisky'} set: {'dog', 'fish', 'cat'}
Duplication
[edit | edit source]Lists and tuples allow duplication. Dictionary and set items are unique.[7]
list = [1, 1, 1]
tuple = (1, 1, 1)
dictionary = {1: 'one', 1: 'one', 1: 'one'}
set = {1, 1, 1}
print("list:", list)
print("tuple:", tuple)
print("dictionary:", dictionary)
print("set:", set)
Output:
list: [1, 1, 1] tuple: (1, 1, 1) dictionary: {1: 'one'} set: {1}
Sets may be used to remove duplication found in other data structures.[8]
list = [1, 1, 1]
tuple = (1, 1, 1)
print("list:", list)
print("set:", set(list))
print("tuple:", tuple)
print("set:", set(tuple))
Output:
list: [1, 1, 1] set: {1} tuple: (1, 1, 1) set: {1}
Looping
[edit | edit source]List, dictionary, tuple, and set items may be accessed using a for loop.[9]
list = ["fish", "dog", "cat"]
tuple = ("fish", "dog", "cat")
dictionary = {
'fish': 'Bubbles',
'dog': 'Spot',
'cat': 'Frisky',
}
set = {"fish", "dog", "cat"}
print("List:")
for item in list:
print(item)
print()
print("Dictionary:")
for item in dictionary:
print(item)
print()
print("Tuple:")
for item in tuple:
print(item)
print()
print("Set:")
for item in set:
print(item)
Output:
List: fish dog cat Dictionary: cat fish dog Tuple: fish dog cat Set: cat fish dog
Index
[edit | edit source]List and tuple items may be accessed by index. Dictionary items are accessed by key. Set items cannot be accessed by index.[10]
list = [1, 2, 3]
dictionary = {1: "one", 2: "two", 3: "three"}
tuple = (1, 2, 3)
set = {1, 2, 3}
for i in range(len(list)):
print("list[%d]: %d" % (i, list[i]))
print()
for key in dictionary:
print("dictionary[%s]: %s" % (key, dictionary[key]))
print()
for i in range(len(tuple)):
print("tuple[%d]: %d" % (i, tuple[i]))
print()
try:
for i in range(len(set)):
print("set[%d]: %d" % (i, set[i]))
except Exception as exception:
print(exception)
Output:
list[0]: 1 list[1]: 2 list[2]: 3 dictionary[1]: one dictionary[2]: two dictionary[3]: three tuple[0]: 1 tuple[1]: 2 tuple[2]: 3 'set' object does not support indexing
Tuple Assignment
[edit | edit source]Python supports having a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time.[11]
x = 1
y = 2
print(x, y)
x, y = y, x
print(x, y)
Output:
1 2 2 1
Set Operations
[edit | edit source]Sets support logical set operations, including membership, subset, superset, union (|), intersection (&), and difference (-).[12]
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
even = {2, 4, 6, 8, 10}
odd = {1, 3, 5, 7, 9}
print("Numbers:", numbers)
print("Even:", even)
print("Odd:", odd)
print("1 in numbers:", 1 in numbers)
print("even.issubset(numbers):", even.issubset(numbers))
print("numbers.issuperset(odd):", numbers.issuperset(odd))
print("even | odd:", even | odd)
print("even & odd:", even & odd)
print("numbers - even:", numbers - even)
Output:
Numbers: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Even: {8, 10, 2, 4, 6} Odd: {9, 1, 3, 5, 7} 1 in numbers: True even.issubset(numbers): True numbers.issuperset(odd): True even | odd: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} even & odd: set() numbers - even: {1, 9, 3, 5, 7}
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- TutorialsPoint
- Wikibooks
Practice
[edit | edit source]- Create a Python program that contains a dictionary of names and phone numbers. Use a tuple of separate first and last name values for the key field. Initialize the dictionary with at least three names and numbers. Ask the user to search for a phone number by entering a first and last name. Display the matching number if found, or a message if not found.
- Create a Python program that contains a dictionary of names and phone numbers. Use a tuple of separate first and last name values for the key field. Allow the user to enter names and numbers and add them to the dictionary. When the user is finished adding entries, display the names and numbers sorted in alphabetical order by last name and first name.
- Create a Python program that asks the user to enter a line of text. Use the string split() method to parse the line and then display the list of words in alphabetical order with any duplicate words removed from the list. Use set() to remove the duplicates.
- Create a Python program that asks the user to enter two sets of comma-separated values. Use the string split() method to parse the line and then use the set() function to covert the lists to sets. Demonstrate set theory for the two sets by displaying the two sets and their relationship to each other as subset, superset, union, intersection, and difference.
Lesson Summary
[edit | edit source]Data Structure Concepts
[edit | edit source]- A data structure is a particular way of organizing data in a computer so that it can be used efficiently.[13]
- Data structures can be used to organize the storage and retrieval of information stored in both main memory and secondary memory.[14]
- The array and record data structures are based on computing the addresses of data items with arithmetic operations; while the linked data structures are based on storing addresses of data items within the structure itself.[15]
- An array is a number of elements in a specific order, typically all of the same type. Elements are accessed using an integer index to specify which element is required. Arrays may be fixed-length or resizable.[16]
- A linked list is a linear collection of data elements of any type, called nodes, where each node has itself a value, and points to the next node in the linked list.[17]
- A record (also called tuple or struct) is an aggregate data structure. A record is a value that contains other values, typically in fixed number and sequence and typically indexed by names. The elements of records are usually called fields or members.[18]
- A class is a data structure that contains data fields, like a record, as well as various methods which operate on the contents of the record.[19]
Python Data Structures
[edit | edit source]- Python data structures include lists, dictionaries, tuples, and sets.[20]
- Python lists are implemented internally as variable-length arrays, rather than linked lists.[21]
- Python dictionaries are implemented internally as resizable hash tables.[22]
- Python tuples are records.[23]
- Python sets are implemented internally as hash tables (like dictionaries) with optimizations that take advantage of the fact that the values are always None.[24]
- The data types for a list, dictionary, tuple, and set, are 'list', 'dict', 'tuple', and 'set', respectively.[25]
- The list(), dict(), tuple(), and set() functions may be used to create list, dictionary, tuple, and set objects, respectively.[26]
- List and dictionary items are mutable. Tuple and set items are immutable.[27]
- Lists and tuples maintain order. Dictionaries and sets are unordered.[28]
- Lists and tuples allow duplication. Dictionary and set items are unique.[29]
- Sets may be used to remove duplication found in other data structures.[30]
- List, dictionary, tuple, and set items may be accessed using a for loop.[31]
- List and tuple items may be accessed by index. Dictionary items are accessed by key. Set items cannot be accessed by index.[32]
- Python supports having a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time.[33]
- Sets support logical set operations, including membership, subset, superset, union, intersection, and difference.[34]
Key Terms
[edit | edit source]- comparable
- A type where one value can be checked to see if it is greater than, less than, or equal to another value of the same type. Types which are comparable can be put in a list and sorted.[35]
- data structure
- A collection of related values, often organized in lists, dictionaries, tuples, etc.[36]
- DSU
- Abbreviation of “decorate-sort-undecorate”, a pattern that involves building a list of tuples, sorting, and extracting part of the result.[37]
- gather
- The operation of assembling a variable-length argument tuple.[38]
- hashable
- A type that has a hash function. Immutable types like integers, floats, and strings are hashable; mutable types like lists and dictionaries are not.[39]
- scatter
- The operation of treating a sequence as a list of arguments.[40]
- shape (of a data structure)
- A summary of the type, size, and composition of a data structure.[41]
- singleton
- A list (or other sequence) with a single element.[42]
- tuple
- An immutable sequence of elements.[43]
- tuple assignment
- An assignment with a sequence on the right side and a tuple of variables on the left. The right side is evaluated and then its elements are assigned to the variables on the left.[44]
Review Questions
[edit | edit source]-
A data structure is _____.A data structure is a particular way of organizing data in a computer so that it can be used efficiently.
-
Data structures can be used to _____.Data structures can be used to organize the storage and retrieval of information stored in both main memory and secondary memory.
-
The array and record data structures are based on _____; while the linked data structures are based on _____.The array and record data structures are based on computing the addresses of data items with arithmetic operations; while the linked data structures are based on storing addresses of data items within the structure itself.
-
An array is _____. Elements are accessed using _____. Arrays may be _____.An array is a number of elements in a specific order, typically all of the same type. Elements are accessed using an integer index to specify which element is required. Arrays may be fixed-length or resizable.
-
A linked list is _____.A linked list is a linear collection of data elements of any type, called nodes, where each node has itself a value, and points to the next node in the linked list.
-
A record (also called tuple or struct) is _____. The elements of records are usually called _____.A record (also called tuple or struct) is an aggregate data structure. A record is a value that contains other values, typically in fixed number and sequence and typically indexed by names. The elements of records are usually called fields or members.
-
A class is _____.A class is a data structure that contains data fields, like a record, as well as various methods which operate on the contents of the record.
-
Python data structures include _____.Python data structures include lists, dictionaries, tuples, and sets.
-
Python lists are implemented internally as _____.Python lists are implemented internally as variable-length arrays, rather than linked lists.
-
Python dictionaries are implemented internally as _____.Python dictionaries are implemented internally as resizable hash tables.
-
Python tuples are _____.Python tuples are records.
-
Python sets are implemented internally as _____.Python sets are implemented internally as dictionaries (hash tables) with keys and no values.
-
The data types for a list, dictionary, tuple, and set, are _____.The data types for a list, dictionary, tuple, and set, are 'list', 'dict', 'tuple', and 'set', respectively.
-
The list(), dict(), tuple(), and set() functions may be used to _____.The list(), dict(), tuple(), and set() functions may be used to create list, dictionary, tuple, and set objects, respectively.
-
List and dictionary items are _____. Tuple and set items are _____.List and dictionary items are mutable. Tuple and set items are immutable.
-
Lists and tuples maintain _____. Dictionaries and sets are _____.Lists and tuples maintain order. Dictionaries and sets are unordered.
-
Lists and tuples allow _____. Dictionary and set items _____.Lists and tuples allow duplication. Dictionary and set items are unique.
-
Sets may be used to remove _____.Sets may be used to remove duplication found in other data structures.
-
List, dictionary, tuple, and set items may be accessed using a _____ loop.List, dictionary, tuple, and set items may be accessed using a for loop.
-
List and tuple items may be accessed by _____. Dictionary items are accessed by _____. Set items _____.List and tuple items may be accessed by index. Dictionary items are accessed by key. Set items cannot be accessed by index.
-
Python supports having a tuple on the left side of an assignment statement. This allows you to _____.Python supports having a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time.
-
Sets support logical set operations, including _____.Sets support logical set operations, including membership, subset, superset, union, intersection, and difference.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Lists and Tuples
- Quiz: Quizlet: Python Lists and Tuples
See Also
[edit | edit source]References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python 3: Tuples
- ↑ Python.org: Built-in Types
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Python.org: Data Structures
- ↑ Python.org: Design and History FAQ
- ↑ Python.org: Design and History FAQ
- ↑ Python.org: Design and History FAQ
- ↑ Quora: How is set implemented internally in Python
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python 3: Tuples
- ↑ Python.org: Built-in Types
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
Lesson 10 - Classes
[edit | edit source]This lesson introduces Python classes.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Object Oriented Programming
- The self
- Classes
- Object Methods and the __init__ method
- Class And Object Variables
- Inheritance
Readings
[edit | edit source]- Wikipedia: Object-oriented programming
- Sthurlow: Python Classes
- Jess Hamrick: An Introduction to Classes and Inheritance (in Python)
Multimedia
[edit | edit source]- YouTube: Python Classes and Objects
- YouTube: Python init
- YouTube: Python Class vs. Instance Variables
- YouTube: Python Inheritance
- YouTube: Python Classes and Objects Playlist
Examples
[edit | edit source]Class Definition
[edit | edit source]Classes are defined using the syntax:[2]
class ClassName:
<statements>
Class Instantiation
[edit | edit source]Classes are instantiated using the syntax:[3]
variable = ClassName()
Class Attributes
[edit | edit source]Class attributes (variables) are defined using the syntax:[4]
class ClassName:
attribute = value
Class Methods
[edit | edit source]Class methods (functions) are defined using the syntax:[5]
class ClassName:
def function(self):
<statements>
Class Initialization
[edit | edit source]Class attributes may be initialized during instantiation using the __init__() method.[6]
class ClassName:
def __init__(self, attribute[, attribute, ...]):
<statements>
Class Example
[edit | edit source]The following example creates a class named Shape with an attribute named sides and a method named perimeter. Three instances of the class are created, one each for a triangle, rectangle, and square. The attribute value and method result are printed for each shape.
class Shape(object):
sides = None
def __init__(self, sides):
self.sides = sides
def perimeter(self):
perimeter = 0
for side in self.sides:
perimeter += side
return perimeter
triangle = Shape([3, 4, 5])
print("triangle sides:", triangle.sides)
print("triangle perimeter:", triangle.perimeter())
rectangle = Shape([4, 2, 4, 2])
print("rectangle sides:", rectangle.sides)
print("rectangle perimeter:", rectangle.perimeter())
square = Shape([2, 2, 2, 2])
print("square sides:", square.sides)
print("square perimeter:", square.perimeter())
Output:
triangle sides: [3, 4, 5] triangle perimeter: 12 rectangle sides: [4, 2, 4, 2] rectangle perimeter: 12 square sides: [2, 2, 2, 2] square perimeter: 8
Inheritance
[edit | edit source]Subclasses are defined using the syntax:[7]
class DerivedClassName(BaseClassName):
<statements>
Inheritance Example
[edit | edit source]The following example creates a class named Shape with an attribute named sides and a method named perimeter. Three subclasses are created named Triangle, Rectangle, and Square. An instance of each subclass is created, and the attribute value and method result are printed for each shape.
class Shape(object):
sides = None
def __init__(self, sides):
self.sides = sides
def perimeter(self):
perimeter = 0
for side in self.sides:
perimeter += side
return perimeter
class Triangle(Shape):
def __init__(self, side1, side2, side3):
self.sides = [side1, side2, side3]
class Rectangle(Shape):
def __init__(self, length, width):
self.sides = [length, width, length, width]
class Square(Shape):
def __init__(self, side):
self.sides = [side, side, side, side]
triangle = Triangle(3, 4, 5)
print("triangle sides:", triangle.sides)
print("triangle perimeter:", triangle.perimeter())
rectangle = Rectangle(4, 2)
print("rectangle sides:", rectangle.sides)
print("rectangle perimeter:", rectangle.perimeter())
square = Square(2)
print("square sides:", square.sides)
print("square perimeter:", square.perimeter())
Output:
triangle sides: [3, 4, 5] triangle perimeter: 12 rectangle sides: [4, 2, 4, 2] rectangle perimeter: 12 square sides: [2, 2, 2, 2] square perimeter: 8
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
[edit | edit source]- Create a Python program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a condition statement to determine their selection, and display their approximate age in the selected timeframe. Perform all calculations using an AgeConverter class that accepts the age in years during initialization and has separate methods that calculate and return the age in months, days, hours, and seconds. Include data validation in the class and error handling in the main program.
- Review MathsIsFun: Conversion of Temperature. Create a Python program that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a condition statement to determine their selection and then gather the appropriate input. Perform all calculations using a TemperatureConverter class that accepts the temperature during initialization and has separate methods that calculate and return the temperature in Celsius and Fahrenheit. Include data validation in the class and error handling in the main program.
- Review MathsIsFun: Area of Plane Shapes. Create a Python program that asks the user what shape they would like to calculate the area for. Use a condition statement to determine their selection and then gather the appropriate input. Perform all area calculations using a Shape main class and subclasses for each selected shape type. Include data validation in the class and error handling in the main program.
- Create a Python program that contains a dictionary of names and phone numbers. Use a class to contain and maintain the dictionary, and use methods to add, update, remove, and search for names and numbers. Include data validation in the class and error handling in the main program.
Lesson Summary
[edit | edit source]Class Concepts
[edit | edit source]- Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.[8]
- A feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated through a notion of "this" or "self".[9]
- Classes define the data format and available procedures for a given type of object and may also contain data and procedures (known as class attributes and methods).[10]
- Objects are instances of classes.[11]
- Class variables belong to the class as a whole; there is only one copy of each one.[12]
- Instance variables or attributes belong to individual objects; every object has its own copy of each one.[13]
- Class methods belong to the class as a whole and have access only to class variables and inputs from the procedure call.[14]
- Instance methods belong to individual objects, and have access to instance variables for the specific object they are called on, inputs, and class variables.[15]
- Classes have a unique namespace so code in one class will not be accidentally confused with the same procedure or variable name in another class.[16]
- Classes provide a layer of abstraction which can be used to separate internal from external code. External code can use an object by calling a specific instance method with a certain set of input parameters, read an instance variable, or write to an instance variable.[17]
- Objects are created by calling a special type of method in the class known as a constructor.[18]
- A program may create many instances of the same class as it runs, which operate independently. This is an easy way for the same procedures to be used on different sets of data.[19]
- Inheritance allows classes to be arranged in a hierarchy that represents "is-a-type-of" relationships. All data and methods available to the parent class also appear in the child class with the same names.[20]
- Subclasses can override the methods defined by superclasses.[21]
Python Classes
[edit | edit source]- Classes are defined using the syntax:[22]
class ClassName:
<statements>
- Classes are instantiated using the syntax:[23]
variable = ClassName()
- Class attributes (variables) are defined using the syntax:[24]
class ClassName:
attribute = value
- Class methods (functions) are defined using the syntax:[25]
class ClassName:
def function(self):
<statements>
- Class attributes may be initialized during instantiation using the __init__() method.[26]
class ClassName:
def __init__(self, attribute[, attribute, ...]):
<statements>
- Subclasses are defined using the syntax:[27]
class DerivedClassName(BaseClassName):
<statements>
Key Terms
[edit | edit source]- attribute
- Data encapsulated within a class or object.[28]
- class
- An extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).[29]
- constructor
- A special type of procedure called to create an object which prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.[30]
- inheritance
- When an object or class is based on another object or class using the same implementation to maintain the same behavior.[31]
- instance
- A concrete occurrence of an object.[32]
- instantiate
- To create an occurrence of an object, typically by calling its constructor.[33]
- method
- A procedure associated with an object.[34]
- object
- A particular instance of a class.[35]
- subclass
- A modular, derivative class that inherits one or more language entities from one or more other classes (called superclasses, base classes, or parent classes).[36]
Review Questions
[edit | edit source]-
Object-oriented programming (OOP) is _____.Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.
-
A feature of objects is _____.A feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated through a notion of "this" or "self".
-
Classes define _____.Classes define the data format and available procedures for a given type of object and may also contain data and procedures (known as class attributes and methods).
-
Objects are _____.Objects are instances of classes.
-
Class variables belong to _____.Class variables belong to the class as a whole; there is only one copy of each one.
-
Instance variables or attributes belong to _____.Instance variables or attributes belong to individual objects; every object has its own copy of each one.
-
Class methods belong to _____.Class methods belong to the class as a whole and have access only to class variables and inputs from the procedure call.
-
Instance methods belong to _____.Instance methods belong to individual objects, and have access to instance variables for the specific object they are called on, inputs, and class variables.
-
Classes have a unique _____.Classes have a unique namespace so code in one class will not be accidentally confused with the same procedure or variable name in another class.
-
Classes provide a layer of abstraction which _____.Classes provide a layer of abstraction which can be used to separate internal from external code. External code can use an object by calling a specific instance method with a certain set of input parameters, read an instance variable, or write to an instance variable.
-
Objects are created by calling _____.Objects are created by calling a special type of method in the class known as a constructor.
-
A program may create many _____ of the same class as it runs, which operate independently. This is an easy way for the same procedures to be used on different sets of data.A program may create many instances of the same class as it runs, which operate independently. This is an easy way for the same procedures to be used on different sets of data.
-
Inheritance allows classes to _____.Inheritance allows classes to be arranged in a hierarchy that represents "is-a-type-of" relationships. All data and methods available to the parent class also appear in the child class with the same names.
-
Subclasses can override _____.Subclasses can override the methods defined by superclasses.
-
Classes are defined using the syntax:Classes are defined using the syntax:
class ClassName:
<statements>
-
Classes are instantiated using the syntax:{{{2}}}
-
Class attributes (variables) are defined using the syntax:{{{2}}}
-
Class methods (functions) are defined using the syntax:Class methods (functions) are defined using the syntax:
class ClassName:
def function(self):
<statements>
-
Class attributes may be initialized during instantiation using the ____ method.Class attributes may be initialized during instantiation using the __init__() method.
class ClassName:
def __init__(self, attribute[, attribute, ...]):
<statements>
-
Subclasses are defined using the syntax:Subclasses are defined using the syntax:
class DerivedClassName(BaseClassName):
<statements>
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Classes
- Quiz: Quizlet: Python Classes
See Also
[edit | edit source]- Python.org: Classes
- PythonBasics: classes and oop tutorial
- SoloLearn: Python
- Open Book Project: Python 3 - Classes and Objects
- Stéphane Ducasse - Free Online Books: Designing Object Systems
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Wikipedia: Object-oriented programming
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Python.org: Classes
- ↑ Wikipedia: Field (computer science)
- ↑ Wikipedia: Class (computer programming)
- ↑ Wikipedia: Constructor (object-oriented programming)
- ↑ Wikipedia: Inheritance (object-oriented programming)
- ↑ Wikipedia: Instance (computer science)
- ↑ Wikipedia: Instance (computer science)
- ↑ Wikipedia: Method (computer programming)
- ↑ Wikipedia: Object (computer science)
- ↑ Wikipedia: Inheritance (object-oriented programming)
Lesson 11 - Modules
[edit | edit source]This lesson introduces Python modules and packages.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Modules
- Byte-compiled .pyc files
- The from ..import ..statement
- A module's __name__ and custom modules
- The dir function and packages
Readings
[edit | edit source]Multimedia
[edit | edit source]Examples
[edit | edit source]Modules
[edit | edit source]Modules are regular Python .py files that define functions or classes that may be imported and reused in other Python programs.[2]
functions.py:
"""This module contains functions that will be imported and reused."""
def function1():
"""Function1"""
print("In function1")
classes.py:
"""This module contains classes that will be imported and reused."""
class Class1(object):
"""Class1"""
def method1(self):
"""method1"""
print("In method1")
The import Statement
[edit | edit source]The import statement finds a module, loads it, initializes it if necessary, and defines a name or names which are used to reference code in the module.[3]
import functions
import classes
functions.function1()
class1 = classes.Class1()
class1.method1()
Output:
In function1 In method1
The from ... import Statement
[edit | edit source]The from...import statement finds a module, loads it, initializes it if necessary, and then adds module references to the local namespace, allowing functions and classes to be accessed without a module reference.[4] Use of import rather than from...import is preferred. While from ... import supports an * option to import all references rather than naming specific functions or classes, this use is discouraged.[5]
from functions import function1
from classes import Class1
function1()
class1 = Class1()
class1.method1()
Output:
In function1 In method1
Module Name
[edit | edit source]When modules are imported, the __name__ variable is set to the name of the module. When the Python interpreter runs a module directly, the __name__ variable is set to "__main__". This allows a module designed to be imported to add a main() function that will only execute when the module is run directly.[6][7]
def main():
"""Used to demonstrate and/or test module code."""
...
if __name__ == "__main__":
main()
The dir() Function
[edit | edit source]The dir() function returns the list of names in the current local scope, or for the object, if specified.[8]
print(dir())
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Wikibooks
Practice
[edit | edit source]- Create a module with at least one function or class. In a separate module, import the first module and use the dir() function to display the names in the local scope. Then import the first module using from ... import * and use the dir() function to display the names in the local scope. Compare the difference between import and from ... import.
- Modify one or more of the Python Programming/Functions#Practice activities so that the function code is in a different module. Use import to import the module and then call the function.
- Modify one or more of the Python Programming/Classes#Practice activities so that the class code is in a different module. Use import to import the module and then instantiate and use the class.
- Review Python.org: os. Import the Python os library and then use getlogin() and uname() to display the current username, computer name, operating system, and version.
Lesson Summary
[edit | edit source]- Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.[9]
- Modules are regular Python .py files that define functions or classes that may be imported and reused in other Python programs.[10]
- The import statement finds a module, loads it, initializes it if necessary, and defines a name or names which are used to reference code in the module.[11]
- The from...import statement finds a module, loads it, initializes it if necessary, and then adds module references to the local namespace, allowing functions and classes to be accessed without a module reference.[12]
- Use of import rather than from...import is preferred.[13]
- While from ... import supports an * option to import all references rather than naming specific functions or classes, this use is discouraged.[14]
- When modules are imported, the __name__ variable is set to the name of the module. When the Python interpreter runs a module directly, the __name__ variable is set to "__main__".[15][16]
- __name__ allows a module designed to be imported to add a main() function that will only execute when the module is run directly.[17][18]
- To speed up loading modules, Python caches the compiled bytecode version of each module.[19]
- A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.[20]
- Python comes with a library of standard modules.[21]
- The sys module provides access to operating system or operating environment variables and functions.[22]
- The dir() function returns the list of names in the current local scope, or for the object, if specified.[23]
Key Terms
[edit | edit source]- bytecode
- A form of instruction set designed for efficient execution by a software interpreter.[24]
Review Questions
[edit | edit source]-
Modular programming is _____.Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.
-
Python modules are _____.Python modules are regular Python .py files that define functions or classes that may be imported and reused in other Python programs.
-
The import statement _____.The import statement finds a module, loads it, initializes it if necessary, and defines a name or names which are used to reference code in the module.
-
The from...import statement _____.The from...import statement finds a module, loads it, initializes it if necessary, and then adds module references to the local namespace, allowing functions and classes to be accessed without a module reference.
-
When importing Python modules, use of _____ rather than _____ is preferred.When importing Python modules, se of import rather than from...import is preferred.
-
While from ... import supports _____, this use is discouraged.While from ... import supports an * option to import all references rather than naming specific functions or classes, this use is discouraged.
-
When modules are imported, the __name__ variable is set to _____. When the Python interpreter runs a module directly, the __name__ variable is set to _____.When modules are imported, the __name__ variable is set to the name of the module. When the Python interpreter runs a module directly, the __name__ variable is set to "__main__".
-
__name__ allows a module designed to be imported to add _____.__name__ allows a module designed to be imported to add a main() function that will only execute when the module is run directly.
-
To speed up loading modules, Python _____.To speed up loading modules, Python caches the compiled bytecode version of each module.
-
A program doesn’t run any faster when it is read from a _____ file than when it is read from a _____ file; the only thing that’s faster about _____ files is _____.A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.
-
Python comes with _____.Python comes with a library of standard modules.
-
The sys module _____.The sys module provides access to operating system or operating environment variables and functions.
-
The dir() function _____.The dir() function returns the list of names in the current local scope, or for the object, if specified.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Modules
- Quiz: Quizlet: Python Modules
See Also
[edit | edit source]- Python.org: Modules
- Python.org: The import system
- SoloLearn: Python
- Open Book Project: Python 3 - Modules
- Real Python: Python Modules and Packages
References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Modules
- ↑ Python.org: The import Statement
- ↑ Python.org: The import Statement
- ↑ Python.org: Modules
- ↑ Python.org: Modules
- ↑ Python.org: __main__
- ↑ Python.org: Dir()
- ↑ Wikipedia: Modular programming
- ↑ Python.org: Modules
- ↑ Python.org: The import Statement
- ↑ Python.org: The import Statement
- ↑ Python.org: Modules
- ↑ Python.org: Modules
- ↑ Python.org: Modules
- ↑ Python.org: __main__
- ↑ Python.org: Modules
- ↑ Python.org: __main__
- ↑ Python.org: Modules
- ↑ Python.org: Modules
- ↑ Python.org: Modules
- ↑ Python.org: sys
- ↑ Python.org: Dir()
- ↑ Wikipedia: Bytecode
Lesson 12 - RegEx
[edit | edit source]This lesson introduces Python regular expression processing.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:
- Standard Library
- Regular expression operations
Readings
[edit | edit source]Multimedia
[edit | edit source]- YouTube: Python for Informatics - Chapter 11 - Regular Expressions
- YouTube: Python - Regular Expressions
- YouTube: Python3 - Regular Expressions
Examples
[edit | edit source]The match() Method
[edit | edit source]The match() method looks for zero or more characters at the beginning of the given string that match the given regular expression and returns a match object if found, or None if there is no match.[1]
import re
string = "<p>HTML text.</p>"
match = re.match("<p>.*</p>", string)
if match:
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
Output:
start: 0 end: 17 group: <p>HTML text.</p>
The search() Method
[edit | edit source]The search() method scans for the first match of the given regular expression in the given string and returns a match object if found, or None if there is no match.[2]
import re
string = "<h1>Heading</h1><p>HTML text.</p>"
match = re.search("<p>.*</p>", string)
if match:
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
Output:
start: 16 end: 33 group: <p>HTML text.</p>
Greedy vs. Non-greedy
[edit | edit source]The '*', '+', and '?' quantifiers are all greedy; they match as much text as possible. Adding ? after the quantifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched.[3]
import re
string = "<h1>Heading</h1><p>HTML text.</p>"
match = re.search("<.*>", string)
if match:
print("Greedy")
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
match = re.search("<.*?>", string)
if match:
print("\nNon-greedy")
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
Output:
Greedy start: 0 end: 33 group: <h1>Heading</h1><p>HTML text.</p> Non-greedy start: 0 end: 4 group: <h1>
The findall() Method
[edit | edit source]The findall() method matches all occurrences of the given regular expression in the string and returns a list of matching strings.[4]
import re
string = "<h1>Heading</h1><p>HTML text.</p>"
matches = re.findall("<.*?>", string)
print("matches:", matches)
Output:
matches: ['<h1>', '</h1>', '<p>', '</p>']
The sub() Method
[edit | edit source]The sub() method replaces every occurrence of a pattern with a string.[5]
import re
string = "<h1>Heading</h1><p>HTML text.</p>"
string = re.sub("<.*?>", "", string)
print("string:", string)
Output:
string: HeadingHTML text.
The split() Method
[edit | edit source]The split() method splits string by the occurrences of pattern.[6]
import re
string = "cat: Frisky, dog: Spot, fish: Bubbles"
keys = re.split(": ?\w*,? ?", string)
values = re.split(",? ?\w*: ?", string)
print("string:", string)
print("keys:", keys)
print("values:", values)
Output:
string: cat: Frisky, dog: Spot, fish: Bubbles keys: ['cat', 'dog', 'fish', ''] values: ['', 'Frisky', 'Spot', 'Bubbles']
The compile() Method
[edit | edit source]The compile() method compiles a regular expression pattern into a regular expression object, which can be used for matching using its match() and search() methods. The expression’s behaviour can be modified by specifying a flags value.[7]
import re
string = "<p>Lines of<br>HTML text</p>"
regex = re.compile("<br>", re.IGNORECASE)
match = regex.search(string)
if match:
print("start:", match.start(0))
print("end:", match.end(0))
print("group:", match.group(0))
Output:
start: 11 end: 15 group: <br>
Match Groups
[edit | edit source]Match groups match whatever regular expression is inside parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed.[8]
import re
string = "<p>HTML text.</p>"
match = re.match("<p>(.*)</p>", string)
if match:
print("start:", match.start(1))
print("end:", match.end(1))
print("group:", match.group(1))
string = "'cat': 'Frisky', 'dog': 'Spot', 'fish': 'Bubbles'"
match = re.search("'cat': '(.*?)', 'dog': '(.*?)', 'fish': '(.*?)'", string)
if match:
print("groups:", match.group(1), match.group(2), match.group(3))
lst = re.findall(r"'(.*?)': '(.*?)',?\s*", string)
for key, value in lst:
print("%s: %s" % (key, value))
Output:
start: 3 end: 13 group: HTML text. groups: Frisky Spot Bubbles cat: Frisky dog: Spot fish: Bubbles
Activities
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- RegexOne
Practice
[edit | edit source]- Create a Python program that asks the user to enter a line of comma-separated grade scores. Use RegEx methods to parse the line and add each item to a list. Display the list of entered scores sorted in descending order and then calculate and display the high, low, and average for the entered scores. Include try and except to handle input errors.
- Create a Python program that asks the user for a line of text that contains HTML tags, such as:
<p><strong>This is a bold paragraph.</strong></p>
Use RegEx methods to search for and remove all HTML tags from the text, saving each removed tag in a list. Print the untagged text and then display the list of removed tags sorted in alphabetical order with duplicate tags removed. Include error handling in case an HTML tag isn't entered correctly (an unmatched < or >). Use a user-defined function for the actual string processing, separate from input and output. - Create a Python program that asks the user to enter a line of dictionary keys and values in the form Key-1: Value 1, Key-2: Value 2, Key-3: Value 3. You may assume that keys will never contain spaces, but may contain hyphens. Values may contain spaces, but a comma will always separate one key-value pair from the next key-value pair. Use RegEx functions to parse the string and build a dictionary of key-value pairs. Then display the dictionary sorted in alphabetical order by key. Include input validation and error handling in case a user accidentally enters the same key more than once.
Lesson Summary
[edit | edit source]RegEx Concepts
[edit | edit source]- A regular expression (abbreviated regex) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings.[9]
- Each character in a regular expression is either understood to be a metacharacter with its special meaning, or a regular character with its literal meaning.[10]
- In regex, | indicates either|or.[11]
- In regex, ? indicates there is zero or one of the preceding element.[12]
- In regex, * indicates there is zero or more of the preceding element.[13]
- In regex, + indicates there is one or more of the preceding element.[14]
- In regex, () is used to group elements.[15]
- In regex, . matches any single character.[16]
- In regex, [] matches any single character contained within the brackets.[17]
- In regex, [^] matches any single character not contained within the brackets.[18]
- In regex, ^ matches the start of the string.[19]
- In regex, $ matches the end of the string.[20]
- In regex, \w matches a word.[21]
- In regex, \d matches a digit.[22]
- In regex, \s matches whitespace.[23]
Python RegEx
[edit | edit source]- The Python regular expression library is re.py, and accessed using
import re
.[24] - The match() method looks for zero or more characters at the beginning of the given string that match the given regular expression and returns a match object if found, or None if there is no match.[25]
- The search() method scans for the first match of the given regular expression in the given string and returns a match object if found, or None if there is no match.[26]
- The '*', '+', and '?' quantifiers are all greedy; they match as much text as possible. Adding ? after the quantifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched.[27]
- The findall() method matches all occurrences of the given regular expression in the string and returns a list of matching strings.[28]
- The sub() method replaces every occurrence of a pattern with a string.[29]
- The split() method splits string by the occurrences of pattern.[30]
- The compile() method compiles a regular expression pattern into a regular expression object, which can be used for matching using its match() and search() methods. The expression’s behaviour can be modified by specifying a flags value.[31]
- The compile() method flags include re.IGNORECASE, re.MULTILINE, and re.DOTALL for case insensitivity and processing more than one line at a time.[32]
- Match groups match whatever regular expression is inside parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed.[33]
Key Terms
[edit | edit source]- brittle code
- Code that works when the input data is in a particular format but is prone to breakage if there is some deviation from the correct format. We call this “brittle code” because it is easily broken.[34]
- greedy matching
- The notion that the “+” and “*” characters in a regular expression expand outward to match the largest possible string.[35]
- grep
- A command available in most Unix systems that searches through text files looking for lines that match regular expressions. The command name stands for "Generalized Regular Expression Parser".[36]
- regular expression
- A language for expressing more complex search strings. A regular expression may contain special characters that indicate that a search only matches at the beginning or end of a line or many other similar capabilities.[37]
- wild card
- A special character that matches any character. In regular expressions the wild-card character is the period.[38]
Review Questions
[edit | edit source]-
A regular expression (abbreviated regex) is _____.A regular expression (abbreviated regex) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings.
-
Each character in a regular expression is either _____, or _____.Each character in a regular expression is either understood to be a metacharacter with its special meaning, or a regular character with its literal meaning.
-
In regex, | indicates _____.In regex,
-
In regex, ? indicates _____.In regex, ? indicates there is zero or one of the preceding element.
-
In regex, * indicates _____.In regex, * indicates there is zero or more of the preceding element.
-
In regex, + indicates _____.In regex, + indicates there is one or more of the preceding element.
-
In regex, () is used to _____.In regex, () is used to group elements.
-
In regex, . matches _____.In regex, . matches any single character.
-
In regex, [] matches _____.In regex, [] matches any single character contained within the brackets.
-
In regex, [^] matches _____.In regex, [^] matches any single character not contained within the brackets.
-
In regex, ^ matches _____.In regex, ^ matches the start of the string.
-
In regex, $ matches _____.In regex, $ matches the end of the string.
-
In regex, \w matches _____.In regex, \w matches a word.
-
In regex, \d matches _____.In regex, \d matches a digit.
-
In regex, \s matches _____.In regex, \s matches whitespace.
-
The match() method _____.The match() method looks for zero or more characters at the beginning of the given string that match the given regular expression and returns a match object if found, or None if there is no match.
-
The search() method _____.The search() method scans for the first match of the given regular expression in the given string and returns a match object if found, or None if there is no match.
-
The '*', '+', and '?' quantifiers are all _____; they match _____. Adding ? after the quantifier makes it _____.The '*', '+', and '?' quantifiers are all greedy; they match as much text as possible. Adding ? after the quantifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched.
-
The findall() method _____.The findall() method matches all occurrences of the given regular expression in the string and returns a list of matching strings.
-
The sub() method _____.The sub() method replaces every occurrence of a pattern with a string.
-
The split() method _____.The split() method splits string by the occurrences of pattern.
-
The compile() method _____.The compile() method compiles a regular expression pattern into a regular expression object, which can be used for matching using its match() and search() methods. The expression’s behaviour can be modified by specifying a flags value.
-
The compile() method flags include _____.The compile() method flags include re.IGNORECASE, re.MULTILINE, and re.DOTALL for case insensitivity and processing more than one line at a time.
-
Match groups match _____.Match groups match whatever regular expression is inside parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Regular Expressions
- Quiz: Quizlet: Python Regular Expressions
See Also
[edit | edit source]- Regular expressions
- Python.org: String Pattern Matching
- SoloLearn: Python
- Regex101.com: Online Regex Tester
- PyRegex.com: Python Regex Tester
- Princeton: Regular Expressions - The Complete Tutorial
References
[edit | edit source]- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Wikipedia: Regular expression
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ Python.org: Regular expression operations
- ↑ PythonLearn: Regular expressions
- ↑ PythonLearn: Regular expressions
- ↑ PythonLearn: Regular expressions
- ↑ PythonLearn: Regular expressions
- ↑ PythonLearn: Regular expressions
Lesson 13 - Files
[edit | edit source]This lesson introduces Python file processing.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Standard Library
- os module
- sys module
- Input Output
- Files I/O
Readings
[edit | edit source]- Wikipedia: File system
- Wikipedia: Directory (computing)
- Wikipedia: Directory structure
- Wikipedia: Text file
- PythonLearn: Automating common tasks on your computer
- Python for Everyone: Files
Multimedia
[edit | edit source]Examples
[edit | edit source]The os.getcwd() Method
[edit | edit source]The os.getcwd() method returns a string representing the current working directory.[2]
import os
print("Current working directory:", os.getcwd())
Output:
Current working directory: /home/ubuntu/workspace
The os.chdir() Method
[edit | edit source]The os.chdir() method changes the current working directory to the given path.[3]
import os
directory = os.getcwd()
print("Current working directory:", directory)
os.chdir("..")
print("Changed to:", os.getcwd())
os.chdir(directory)
print("Changed back to:", directory)
Output:
Current working directory: /home/ubuntu/workspace Changed to: /home/ubuntu Changed back to: /home/ubuntu/workspace
The os.path.isdir() Method
[edit | edit source]The os.path.isdir() method returns True if the given path is an existing directory.[4]
import os
path = os.getcwd()
if os.path.isdir(path):
print("Current working directory exists.")
else:
print("Current working directory does not exist.")
Output:
Current working directory exists.
The os.path.join() Method
[edit | edit source]The os.path.join() method joins one or more path components intelligently, avoiding extra directory separator (os.sep) characters.[5]
import os
path = os.getcwd()
directory = os.path.join(path, "__python_demo__")
print("path:", path)
print("directory:", directory)
Output:
path: /home/ubuntu/workspace directory: /home/ubuntu/workspace/__python_demo__
The os.mkdir() Method
[edit | edit source]The os.mkdir() method creates a directory with the given path.[6]
import os
path = os.getcwd()
directory = os.path.join(path, "__python_demo__")
if os.path.isdir(directory):
raise Exception("Path already exists. Can't continue.")
os.mkdir(directory)
The os.rmdir() Method
[edit | edit source]The os.rmdir() method removes (deletes) the directory with the given path.[7]
import os
path = os.getcwd()
directory = os.path.join(path, "__python_demo__")
if os.path.isdir(directory):
raise Exception("Path already exists. Can't continue.")
os.mkdir(directory)
print("Created directory:", directory)
os.chdir(directory)
print("Changed to:", os.getcwd())
os.chdir(path)
print("Changed back to:", os.getcwd())
os.rmdir(directory)
print("Removed directory:", directory)
Output:
Created directory: /home/ubuntu/workspace/__python_demo__ Changed to: /home/ubuntu/workspace/__python_demo__ Changed back to: /home/ubuntu/workspace Removed directory: /home/ubuntu/workspace/__python_demo__
The os.walk() Method
[edit | edit source]The os.walk() method generates the subdirectories and files in a given path as a 3-tuple of a path string with subdirectory list and filename list.[8]
import os
for path, directories, files in os.walk(os.getcwd()):
for directory in directories:
print(os.path.join(path, directory))
for file in files:
print(os.path.join(path, file))
Output:
... <all subdirectories and files in the current working directory>
The os.path.isfile() Method
[edit | edit source]The os.path.isfile() method returns True if the given path is an existing file.[9]
path = os.getcwd()
filename = os.path.join(path, "__python_demo.tmp")
if os.path.isfile(filename):
print("File exists.")
else:
print("File does not exist.")
Output:
File does not exist.
The open() Function
[edit | edit source]The open() function opens the given file in the given mode (read, write, append) and returns a file object.[10]
file = open(filename, "r") # read
file = open(filename, "w") # write
file = open(filename, "a") # append
file = open(filename, "r+") # read + write
file = open(filename, "w+") # read + write (new / cleared file)
file = open(filename, "a+") # read + append (position starts at end of file)
The file.write() Method
[edit | edit source]The file.write() method writes the contents of the given string to the file, returning the number of characters written.[11]
file.write("Temporary Python Demo File")
The file.close() Method
[edit | edit source]The file.close() method closes the file and frees any system resources taken up by the open file.[12]
import os
path = os.getcwd()
filename = os.path.join(path, "__python_demo.tmp")
file = open(filename, "w")
file.write("Temporary Python Demo File")
file.close()
if os.path.isfile(filename):
print("Created %s" % filename)
Output:
Created /home/ubuntu/workspace/__python_demo.tmp
The file.read() Method
[edit | edit source]The file.read() method reads the given number of bytes from the file, or all content if no size is given, and returns the bytes that were read.[13]
import os
path = os.getcwd()
filename = os.path.join(path, "__python_demo.tmp")
if os.path.isfile(filename):
file = open(filename, "r")
text = file.read()
file.close()
print("File text:", text)
Output:
File text: Temporary Python Demo File
Reading Lines
[edit | edit source]For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code.[14]
import os
path = os.getcwd()
filename = os.path.join(path, "__python_demo.tmp")
file = open(filename, "r")
for line in file:
print(line, end='')
file.close()