Sign in

Intro to Computer Science / Unit 5: Conditionals and Boolean Logic

5.2 If, Else and Elif

3 practice questionsNot yet reviewed

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.
  • else runs 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?
With n = 4, what does if n > 5: print("big") followed by else: print("small") display?
What is the purpose of elif?

Ready for more? Take the Unit 5 test.