Skip to main content
Python provides several control flow tools beyond the while statement. Let’s explore if statements, for loops, functions, and more advanced concepts.

if Statements

The if statement is used for conditional execution:
Key points:
  • Zero or more elif parts
  • The else part is optional
  • elif is 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’s for statement iterates over items of any sequence (list, string, etc.) in the order they appear:

Modifying Collections While Iterating

Modifying a collection while iterating over it can be tricky. Instead, iterate over a copy or create a new collection:

The range() Function

To iterate over a sequence of numbers, use range():
range() with start, stop, and step:
Combining range() with len():
In most cases, use enumerate() instead of range(len()) for cleaner code.

break and continue Statements

break

The break statement exits the innermost loop:

continue

The continue statement skips to the next iteration:

else Clauses on Loops

Loops can have an else 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

The pass statement does nothing. It’s used when a statement is required syntactically but no action is needed:

match Statements

The match statement (Python 3.10+) compares a value against patterns:

Combining Patterns

Pattern Matching with Unpacking

Pattern Matching with Classes

Defining Functions

Use the def keyword to create a function:
Key concepts:
  • The first statement can be a docstring
  • Functions without an explicit return statement return None
  • 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:
This function can be called:
  • 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!')
Important: Default values are evaluated only once at function definition time:
Use None as the default to avoid this:

Keyword Arguments

Functions can be called using keyword arguments:
Valid calls:

Lambda Expressions

Small anonymous functions can be created with lambda:
Lambdas can be used as arguments:

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

Next Steps

Now that you understand control flow and functions, learn about Data Structures including lists, tuples, sets, and dictionaries.