The if statement
- Python course
- Beginner
- Lesson 36/116
- 4 min
Learn condition checks with if.
The if statement
An if statement runs a block when a condition is true. The condition goes after if, before a colon:
age = 18
if age >= 18:
print("Adult")When the condition is True it runs the indented block; when False it skips it. Indentation defines the block; four spaces is standard. This structure is the basis of decisions.
The boundary of the if block
Indentation shows where the if block ends. Indented lines are part of the block; when indentation stops, the block ends.
if True:
print("Inside the block")
print("Still inside")
print("Outside the block")Inconsistent indentation raises IndentationError. All lines in a block must share the same indent.
Practice Print a decision with if
Assign score = 85. Inside an if score >= 50: block, print print("Passed").
Starter code
# Decision with ifSample solution
score = 85
if score >= 50:
print("Passed")Expected output
Passed
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If age is 20, what does if age >= 18: print("Adult") do?
- Nothing
- Raises an error
- Prints Adult Correct answer
- Runs else
Explanation: 20 >= 18 is True, so print runs.
2 Complete the if condition
age = 18
if age ____ 18:
print("Adult")
age = 18
if age >= 18:
print("Adult")
Explanation: >= is the greater-or-equal comparison.
3 Match the if concepts
| Term | Meaning |
|---|---|
if |
Condition |
: |
Opening a block |
indent |
Defining the block |
True |
Condition is true |