Intro to Computer Science / Unit 5: Conditionals and Boolean Logic
5.2 If, Else and Elif
Notes
An if statement runs a block of code only when its condition is True. The block is indented.
score = 72
if score >= 90:
print("A")
elif score >= 70:
print("C or better")
else:
print("Keep trying")
- Python checks conditions top to bottom and runs only the first block whose condition is True.
elseruns when no earlier condition was True. A colon:ends each condition line.- This prints
C or better: 72 is not at least 90, but it is at least 70.
Practice
What does the code above print if
score = 95?95 >= 90 is True, so only the first block runs.
With
n = 4, what does if n > 5: print("big") followed by else: print("small") display?4 > 5 is False, so the else block runs.
What is the purpose of
elif?elif means "else if" and adds more conditions to a chain.
Ready for more? Take the Unit 5 test.