Python if and else Statements
Core idea
An if statement runs its indented block when its condition is true in a truth test. An optional else block runs when that condition is false. Write a colon after each header and indent its body consistently (four spaces is the usual convention). The headers of if and its matching else align.
stock = 0if stock > 0: print("Available")else: print("Sold out")Only the else block runs because stock is not positive. Changing stock to 2 selects the if block.
Set a value in either branch
amount = 60if amount >= 50: fee = 0else: fee = 5print(amount + fee)Both branches assign fee, so the final unindented print can use it regardless of the choice. At exactly 50 the fee is zero.
Use an optional if
An else is not required. The assignment runs only for false-in-a-truth-test label values; the final print always runs.
Common mistake
An else does not take a condition. A statement indented inside a branch runs only when that branch is chosen; a statement aligned with if runs after the conditional.
Practice
Write an if/else that prints Full when seats == 0 and Open otherwise. Test zero and a positive number.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
If and else
Check your understanding of if and else.
What is printed?
amount = 50if amount >= 50: print("Free")else: print("Paid")What is printed?
stock = 8if stock < 3: print("Low")print("Done")Which header is valid for the fallback branch of an if statement?
What is printed?
amount = 20if amount >= 50: fee = 0else: fee = 5print(fee)