Find a course

Module 3: Decisions and LoopsLesson 6 of 1212 min

Making Decisions With if

Compare values, branch with if, elif and else, combine conditions with and, or and not, and understand indentation and truthy values.

Step 1 of 14Learn

Comparisons produce True or False

A parking app charges nothing for the first 30 minutes, $2 per hour after that, and caps the daily price at $15. Every one of those rules is a question with a yes-or-no answer. Programs answer such questions with comparison operators, which always produce a Boolean, True or False:

OperatorMeaningExample (x = 7)Result
==equal tox == 7True
!=not equal tox != 7False
<less thanx < 5False
>greater thanx > 5True
<=less than or equalx <= 7True
>=greater than or equalx >= 10False

Python allows chained comparisons that read like math: 18 <= age < 65 is true for ages 18 through 64.

Strings can be compared too, but carefully. "apple" == "Apple" is False, because comparisons are case sensitive (unlike Excel). Normalize first: answer.lower() == "yes". Ordering compares character codes, so "Zebra" < "apple" is True (all capitals come before lowercase letters).

Comparing different types for equality is allowed but usually signals a bug: 5 == "5" is simply False, which is what happens when you forget to convert input(). Ordering comparisons like 5 < "5" raise a TypeError.

Step 2 of 14Learn

if, else and the meaning of indentation

An if statement runs a block of code only when a condition is true:

minutes = int(input("Minutes parked: "))
if minutes <= 30:
    print("Free parking!")
    fee = 0
else:
    fee = 2 * (minutes / 60)
    print(f"Fee: {fee:.2f}")
print("Thank you for visiting.")

Three details make this work:

  1. The if line ends with a colon. So does else:.
  2. The lines that belong to each branch are indented, by convention 4 spaces. Indentation is not decoration in Python; it is the structure. The indented lines form a block.
  3. The first line that returns to the left margin, print("Thank you…"), is outside both branches, so it runs no matter what.

Exactly one of the two blocks runs: the if block when the condition is true, the else block otherwise. else is optional; without it, nothing special happens when the condition is false.

Most editors insert 4 spaces when you press Tab inside a Python file. Mixing tabs and spaces, or indenting one line of a block by 3 spaces and the next by 4, produces an IndentationError. If you see one, check that every line of the block lines up exactly.

Step 3 of 14Practice · Diagram

The parking fee as a decision tree

A car is parked for 20 minutes. Tap the leaf it ends at.

Tap the shape that answers the question, then press Check.

The parking fee as a decision treeHierarchy diagram: minutes <= 30?, Yes: fee = 0, No: hourly fee > 15?, Yes: fee = 15 (cap), No: fee = $2 per hour.minutes <= 30?Yes: fee = 0No: hourly fee > 15?Yes: fee = 15 (cap)No: fee = $2 per hour
minutes <= 30?
Yes: fee = 0
No: hourly fee > 15?
Yes: fee = 15 (cap)
No: fee = $2 per hour

Step 4 of 14Practice · What would you do?

What would you do?

What does this program print when temp = 12?

temp = 12
if temp > 25:
    print("Hot")
    print("Drink water")
print("Have a nice day")

Step 5 of 14Learn

More than two paths: elif

When there are several possible outcomes, chain conditions with elif (short for "else if"):

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)     # B

Python checks the conditions from top to bottom and runs only the first block whose condition is true; all the rest are skipped, even if they would also be true. A score of 85 fails >= 90, passes >= 80, gets "B", and Python never looks at the remaining tests. The final else catches everything that matched nothing.

Because only the first match runs, order matters. If you put score >= 70 first, a score of 95 would get "C". Arrange conditions from most specific (or strictest) to least.

Compare this with several separate if statements in a row. Each separate if is checked independently, so a score of 95 could trigger all of them, overwriting grade each time and ending with whatever the last true test assigned. Use elif when the outcomes are mutually exclusive, and separate if statements when several things may be true at once, such as independent warnings.

Step 6 of 14Practice · Diagram

Which grade does each score get?

Tap the score that sits exactly on a boundary and gets a B.

Tap the shape that answers the question, then press Check.

Which grade does each score get?Scale: 55, 72, 80, 95.FCBA0204060801005555727280809595
55

55

72

72

80

Fails >= 90, passes >= 80: grade B.

95

95

Step 7 of 14Practice · Fill in the blanks

Fill in the blanks

Complete the shipping rule: orders of 50 or more ship free, orders of 25 or more pay 4.99, all others pay 7.99. if total >= 50: shipping = 0 / total >= 25: shipping = 4.99 / : shipping = 7.99

Step 8 of 14Learn

Combining conditions and truthiness

Three logical operators combine conditions:

  • and: true only if both sides are true. age >= 18 and has_ticket
  • or: true if at least one side is true. day == "Sat" or day == "Sun"
  • not: flips a Boolean. not is_member

A common mistake is writing day == "Sat" or "Sun". Python reads that as (day == "Sat") or ("Sun"), and a non-empty string counts as true, so the condition is always true. Write the comparison out on both sides, or use membership: day in ("Sat", "Sun").

That brings up truthiness. In a condition, Python treats these values as false ("falsy"): False, 0, 0.0, the empty string "", empty collections like [] and {}, and None. Everything else is true ("truthy"). So you can write:

name = input("Name: ").strip()
if not name:
    print("You didn't type a name.")

and and or also short-circuit: Python stops evaluating as soon as the answer is known. In count > 0 and total / count > 10, the division never runs when count is 0, which neatly avoids a ZeroDivisionError.

Step 9 of 14Compare

and / or truth table

AspectA and BA or B
A True, B TrueTrueTrue
A True, B FalseFalseTrue
A False, B TrueFalseTrue
A False, B FalseFalseFalse

Step 10 of 14Practice · Code challenge · Python

A museum charges by age: children under 12 pay 5, visitors 65 or older pay 7, and everyone else pays 12. Complete ticket_price(age) so it returns the right price.

Real Python, running in a sandbox in your browser.
  • ticket_price(8)
  • ticket_price(30)
  • ticket_price(70)
  • ticket_price(12)
  • ticket_price(65)

Step 11 of 14Practice · True or false

The line if price = 100: is a valid way to check whether price equals 100.

Step 12 of 14Practice · Select all that apply

Which of these values are falsy, meaning an if statement treats them as false? Select all that apply.

Select all that apply.

Step 13 of 14Note

Step 14 of 14Practice · Spot the mistake

Each token is one line of a program (indented lines are marked). Tap the lines that contain errors.