while statement. Let’s explore if statements, for loops, functions, and more advanced concepts.
if Statements
Theif statement is used for conditional execution:
- Zero or more
elifparts - The
elsepart is optional elifis short for “else if” and helps avoid excessive indentation
For comparing the same value to several constants, consider using the
match statement (covered below).for Statements
Python’sfor statement iterates over items of any sequence (list, string, etc.) in the order they appear:
Modifying Collections While Iterating
The range() Function
To iterate over a sequence of numbers, userange():
break and continue Statements
break
Thebreak statement exits the innermost loop:
continue
Thecontinue statement skips to the next iteration:
else Clauses on Loops
Loops can have anelse clause that executes when the loop finishes without hitting a break:
The
else clause belongs to the for loop, not the if statement. It runs when no break occurs.pass Statements
Thepass statement does nothing. It’s used when a statement is required syntactically but no action is needed:
match Statements
Thematch statement (Python 3.10+) compares a value against patterns:
Combining Patterns
Pattern Matching with Unpacking
Pattern Matching with Classes
Defining Functions
Use thedef keyword to create a function:
- The first statement can be a docstring
- Functions without an explicit
returnstatement returnNone - Variables assigned in a function are stored in the local symbol table
Returning Values
More on Defining Functions
Default Argument Values
Specify default values for arguments:ask_ok('Do you really want to quit?')ask_ok('OK to overwrite the file?', 2)ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
Keyword Arguments
Functions can be called using keyword arguments:Lambda Expressions
Small anonymous functions can be created withlambda:
Function Annotations
Annotations are optional metadata about types:Coding Style
Follow PEP 8 for consistent Python code:- Use 4-space indentation (no tabs)
- Wrap lines at 79 characters
- Use blank lines to separate functions and classes
- Use docstrings
- Use spaces around operators:
a = f(1, 2) + g(3, 4) - Name classes with
UpperCamelCase - Name functions and methods with
lowercase_with_underscores - Use UTF-8 encoding
