if / elif / else

Part of the free LogicWiz Python course, Module 2: Decisions and loops. The examples and practice run in the app.

Riya scored 92 and the grade app said C. Every condition in it was correct. Only their order was wrong.

You'll learn to

  • Compare values with == != < > <= >=
  • Write if / else blocks with a colon and indentation
  • Build elif ladders where the order is right
  • Never mix up = and ==

Learn

Comparisons give True or False

marks = 72
print(marks > 40)
print(marks == 100)
print(marks != 72)
print(marks <= 72)
print(5 == 5.0)

== asks "are these equal?" and gives a bool: True or False. != means "not equal". An int and a float with the same value are equal.

if / else: two roads

bill = 250
if bill > 200:
    print("Free chai!")
    print("Enjoy")
else:
    print("Add Rs", 201 - bill, "for free chai")
print("Thank you")

Step through it, then change bill to 150 and run again. Only one of the two blocks runs. Thank you is not indented, so it runs either way.

Colon, then indent

The colon : at the end of if …: and else: opens a block.

  • Every line of the block is indented by the same amount (4 spaces is the standard).
  • The block ends when a line goes back to the left edge.
  • Forget the colon and you get SyntaxError. Indent unevenly and you get IndentationError.

Other languages use { } for blocks. Python uses indentation, so spacing is part of the meaning.

= stores a value (marks = 100). == compares (marks == 100). if marks = 100: is a SyntaxError. Read == aloud as "is equal to" and you will not mix them up.

An elif ladder: grades

marks = int(input())
if marks >= 90:
    print("A")
elif marks >= 75:
    print("B")
elif marks >= 50:
    print("C")
else:
    print("Needs improvement")

Python checks from the top and runs only the first branch that is True, then skips the rest. 82 fails >= 90, passes >= 75, prints B and is done. Change the input line (82) and try 95, 50 and 12.

Why order matters

marks = 92
if marks >= 50:
    print("C")
elif marks >= 75:
    print("B")
elif marks >= 90:
    print("A")

This is Riya's bug. 92 is >= 50, so the first branch wins and the better grades are never checked. In a ladder, put the strictest condition first (highest marks, biggest bill, top slab).

Board practicals ask for these as programs: even or odd, positive / negative / zero, grade from marks, electricity bill by slabs, discount by bill amount. Each is an if / elif / else with the right order. Write the conditions from the strictest down.

In one line

== compares and = stores; an elif ladder runs only the first True branch, so put the strictest condition first.