Skip to content

Chapter 3 of 7

Control Flow

Python's control flow begins with the if statement, written as if condition: followed by an indented block. The condition is evaluated for truthiness; in Python, non-empty and non-zero values are considered truthy, while empty collections, zero, and None are falsy. To chain additional conditions, you can use elif (else-if) clauses, and a final else clause executes when no prior conditions match.

Loops allow you to repeat actions. The while loop, written as while condition:, repeatedly executes its indented block as long as the condition remains truthy. Care must be taken to avoid infinite loops by ensuring the condition eventually becomes false. The for loop, written as for item in iterable:, iterates over sequences such as lists, strings, or the numbers produced by range(). The expression range(n) generates the sequence from 0 to n-1.

Three special statements give you fine-grained control within loops. The break statement exits the loop entirely, while continue skips the rest of the current iteration and proceeds to the next one. The pass statement is a no-op placeholder, useful when syntax requires a statement but no action is needed, such as defining an empty class or function body.

All chapters
  1. 1Introduction to Python
  2. 2Variables, Types, and Operators
  3. 3Control Flow
  4. 4Functions
  5. 5Data Structures
  6. 6Object-Oriented Programming
  7. 7Modules, Exceptions, and Advanced Features

Drill it

Reading is not remembering. These come from the Python Programming deck:

Q

What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple paradigms including procedural, object-o...

Q

Who created Python and when?

Guido van Rossum created Python, with the first version released in 1991. It was named after the British comedy series Monty Python.

Q

What are the key features of Python?

Python features dynamic typing, automatic memory management, extensive standard library, and cross-platform compatibility. It emphasizes code readability with s...

Q

How do you run a Python script from the command line?

Save the code in a file with .py extension, then run python filename.py in the terminal. Use python3 if Python 2 is also installed.