Understand how Python statements execute sequentially to manipulate data and control program flow.
What it is
A statement in Python is an instruction that the interpreter executes. Unlike expressions, which evaluate to a value, statements perform actions such as assigning variables, importing modules, or controlling flow. The fundamental mental model is sequential execution: Python reads code from top to bottom, executing each statement one by one unless a control structure (like if or for) alters the path. Key related terms include assignment, control flow, and indentation.
Why it matters
- Data Manipulation: Statements allow you to store, retrieve, and modify data using variables.
- Logic Control: Conditional and loop statements enable programs to make decisions and repeat tasks.
- Modularity: Function definition statements (
def) organize code into reusable blocks. - Error Handling: Try-except statements manage unexpected errors gracefully.
- Readability: Proper use of statements and indentation makes code easier for humans to understand.
Syntax or steps
The simplest statement is an assignment. It follows the pattern variable = expression. No semicolons are required at the end of lines. Indentation is critical for block statements like loops and functions; standard practice is four spaces per level.
Example
# Simple assignment and arithmetic statement
x = 10
y = x + 1
# Control flow statement
if y > 5:
print("Y is greater than 5")
else:
print("Y is not greater than 5")
# Loop statement
for i in range(3):
print(f"Loop iteration: {i}")
This example demonstrates three core types of statements. First, x = 10 assigns an integer to variable x. Second, y = x + 1 calculates a new value based on x. Third, the if-else block checks a condition and prints a message accordingly. Finally, the for loop iterates three times, printing the current index. Note the consistent four-space indentation inside the if and for blocks.
Common mistakes
- Inconsistent Indentation: Mixing tabs and spaces causes
IndentationError. Always use spaces (typically 4). - Missing Colon: Compound statements like
if,for, anddefrequire a colon:at the end of the header line. - Variable Name Conflicts: Using built-in names like
listorstras variable names can shadow functionality. - Unreachable Code: Placing statements after a
returnorbreakwithin the same block will never execute.
When to use it
Statements are the primary building blocks for imperative programming. Compare them with expressions:
| Feature | Statement | Expression |
|---|---|---|
| Purpose | Performs an action | Evaluates to a value |
| Example | x = 5 | 5 + 3 |
| Return Value | None (usually) | A specific data type |
| Usage | Control flow, assignments | Calculations, conditions |
Use statements when you need to change state or control execution order. Use expressions when you need to compute values for those statements.
Practice
Guided Exercise: Write a script that initializes score = 85. Use an if-elif-else statement to print "A" if score is 90+, "B" if 80-89, and "C" otherwise.
Challenge: Create a list of numbers [1, 2, 3]. Use a for loop to calculate their sum and assign it to a variable total. Print total.
Hint: Initialize total = 0 before the loop. Inside the loop, use total += num.
Quick check
Question: What happens if you forget the colon at the end of an if statement?
Answer: Python raises a SyntaxError because the parser expects a compound statement header to end with a colon.
Summary
Python statements are instructions that execute actions, distinct from expressions that return values. Mastery of basic assignment, control flow, and proper indentation is essential for writing functional and readable Python code.