16. if / elif / else

So far, programs ran the same way every time. This chapter adds a condition: a question answered True or False. That answer decides which block of code runs.

Comparing values

Conditions are built from comparison operators. Each compares two values and returns a boolean.

Operator Meaning
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
print(7 == 7)     # True
print(7 == 8)     # False
print("a" == "A") # False  (case matters)
print(7 != 8)     # True
print(3 < 5)      # True
print(3 >= 3)     # True

The equality operator is == (two equals signs). A single = is assignment — it changes a variable. So if x = 7 is a syntax error; Python refuses to run it.

The if statement

if runs a block of code only when its condition is true.

age = 16
if age >= 18:
    print("You can vote.")

Read it left to right: if the age is at least 18, print the message. The colon at the end of the if line is required. The body must be indented — four spaces is the standard. Python uses the indentation itself to know where the block ends. There is no end keyword.

else for the other case

else runs when the condition is false. With if, it covers both possibilities exactly once:

age = 16
if age >= 18:
    print("You can vote.")
else:
    print("Not old enough to vote yet.")

Exactly one print line runs, never both.

elif for chains

For more than two cases, chain them with elif (short for "else if"). Python tries each in order and stops at the first true one:

score = 73
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Order matters: Python takes the first match. With score >= 60 on top, every passing grade would get a D — nobody would see A, B, or C.

Open exercises/16/01-grade.py. Change the score and run it. Try values right at the boundaries (60, 70, 80, 90) to confirm >= includes them.

Combining conditions with and, or, not

Sometimes one comparison is not enough. Python has three logical operators that combine booleans:

Operator Meaning
and true if both sides are true
or true if either side is true
not flips true to false and false to true
level = 12
has_key = True

if level >= 10 and has_key:
    print("You can enter the dungeon.")

if level < 10 or not has_key:
    print("You are blocked.")

Spell them out as words. Python does not use &&, ||, or !.

Truthy and falsy

The conditions above all produce real booleans, but if accepts any value. Python's rule:

  • None, False, 0, 0.0, "", and empty collections are falsyif skips the block.
  • Everything else is truthy.

In Python, 0 and "" are falsy. Checking whether a variable has a value:

name = input()
if name:
    print("Hello, " + name)
else:
    print("No name was entered.")

Open exercises/16/02-truthy.py and run it. Compare the output to what you expected. In Python, 0 and "" are falsy — keep that in mind.

Homework

Problem 1 — Even or odd

Open exercises/16/homework/01-even-or-odd.py. Prompt for a number. Print even or odd based on whether n % 2 is 0.

Problem 2 — Roblox level gate

Open exercises/16/homework/02-level-gate.py. Two variables sit at the top: level (a number) and has_key (a boolean). Print You can enter the dungeon. only when the player is at least level 10 and has the key. Otherwise print one of:

  • Level too low. (if the level alone is the problem),
  • Missing the key. (if the level is fine but the key is missing),
  • Level too low and missing the key. (if both are wrong).

Problem 3 — Grade letter

Open exercises/16/homework/03-grade-letter.py. Prompt for a score (0 to 100). Print the grade letter A, B, C, D, or F using the same cutoffs as the example in this chapter.

Challenge — Largest of three

Open exercises/16/homework/04-largest-of-three.py. Three variables hold three numbers. Print the largest, using if and the comparison operators — no loops, no lists, no max(). The twist: handle ties cleanly (if two numbers tie for largest, print one of them).

Stuck or finished? Open the homework solutions page.