Find a course

Module 3: Decisions and LoopsLesson 5 of 1012 min

Making Decisions With if

Use comparison operators, if, elif and else, plus and, or and not, so your programs react differently to different situations.

Step 1 of 14Learn

Programs that choose

A ride at an amusement park has a sign: You must be at least 120 cm tall. A ticket gate checking that sign is making a decision, and programs do the same with an if statement:

height = int(input("Height in cm: "))
if height >= 120:
    print("Enjoy the ride!")
else:
    print("Sorry, not tall enough yet.")
print("Next!")

The part after if is a condition: an expression that is either True or False. If it's True, the indented block under if runs. Otherwise, the block under else runs. Exactly one of the two runs, never both.

Three details matter:

  1. The if and else lines end with a colon :.
  2. The lines inside each block are indented, normally by 4 spaces. In Python, indentation isn't decoration; it's how Python knows which lines belong to the block.
  3. print("Next!") is back at the left edge, so it's outside the if/else and runs every time.

else is optional. Without it, the program simply skips the block when the condition is False.

Step 2 of 14Practice · Diagram

Anatomy of an if statement

Which part decides whether the block runs?

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

Anatomy of an if statementParts diagram: if statement, if keyword, Condition, Colon :, Indented block, else: (optional).if statementif keywordConditionColon :Indented blockelse: (optional)
if statement
if keyword
Condition

Something that is True or False, like height >= 120.

Colon :

Forget it and you get a SyntaxError.

Indented block

Runs only when the condition is True. Usually 4 spaces.

else: (optional)

Runs when the condition is False.

Step 3 of 14Practice · Match the pairs

Match each comparison operator to its meaning.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. ==
  2. !=
  3. >=
  4. <

Step 4 of 14Learn

More than two paths: elif

Many decisions have more than two outcomes. A grade calculator might turn a score into a letter. Use elif, short for "else if":

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

Python checks the conditions top to bottom and runs only the first block whose condition is True. Then it skips the rest. With 84, score >= 90 is False, score >= 80 is True, so grade becomes "B" and the remaining checks are never looked at.

That's why order matters. If you put score >= 70 first, a score of 95 would get a "C", because 95 >= 70 is True and Python would stop there. When conditions overlap, check the strictest one first.

A common mistake is using several separate if statements instead of elif. Separate ifs are all checked independently, so more than one block can run and later ones can overwrite earlier results.

Step 5 of 14Practice · Diagram

The grade checks, as a decision tree

Python tests the conditions top to bottom and stops at the first one that is True.

Where does a score of 84 end up?

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

The grade checks, as a decision treeHierarchy diagram: score >= 90?, Yes: A, No: score >= 80?, Yes: B, No: score >= 70?, Yes: C, No: lower grade.score >= 90?Yes: ANo: score >= 80?Yes: BNo: score >= 70?Yes: CNo: lower grade
score >= 90?
Yes: A
No: score >= 80?
Yes: B
No: score >= 70?
Yes: C
No: lower grade

Step 6 of 14Practice · Choose one

What does this print? `` temp = 31 if temp > 25: print("Hot") elif temp > 30: print("Very hot") else: print("OK") ``

Step 7 of 14Learn

Combining conditions

Sometimes one test isn't enough. Python has three logical operators:

  • and: True only if both sides are True.
  • or: True if at least one side is True.
  • not: flips True to False and False to True.
age = 15
has_ticket = True
if age >= 13 and has_ticket:
    print("Welcome to the movie")

day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("Weekend!")

game_over = False
if not game_over:
    print("Keep playing")

A tempting shortcut is wrong: if day == "Saturday" or "Sunday":. Python reads it as (day == "Saturday") or ("Sunday"), and a non-empty string counts as True, so the condition is always True, even on a Tuesday. Write the full comparison on both sides of or.

Python also allows chained comparisons that read like math: 13 <= age <= 19 is True for teen ages. Use whichever form you find clearer.

Step 8 of 14Compare

Truth table for and / or

Aspecta and ba or b
a True, b TrueTrueTrue
a True, b FalseFalseTrue
a False, b TrueFalseTrue
a False, b FalseFalseFalse

Step 9 of 14Practice · Sort into groups

Sort these conditions by their value when x = 7 and y = 3.

Tap an item, then tap its group (or drag it there).

Step 10 of 14Practice · Code challenge · Python

Code challenge · Python

Complete letter_grade(score) so it returns the letter for a test score:

  • 90 or more: "A"
  • 80 to 89: "B"
  • 70 to 79: "C"
  • 60 to 69: "D"
  • below 60: "F"

For example, letter_grade(84) returns "B".

The def line and the return are already written for you; you will learn exactly how they work in the Functions lesson. Fill in the middle.

Real Python, running in a sandbox in your browser.
  • letter_grade(84)
  • letter_grade(97)
  • letter_grade(90)
  • letter_grade(60)
  • letter_grade(59)

Step 11 of 14Note

Step 12 of 14Practice · Spot the mistake

This program should print "Free shipping" when the order total is 50 or more. Tap the lines with errors.

Step 13 of 14Practice · Fill in the blanks

Fill in the blanks

Complete the check so it prints "Access granted" only when the password is correct and the user is not locked out. if password == "dragon42" locked: print("Access granted")

Step 14 of 14Practice · What would you do?

What would you do?

You're writing a ticket-price program: kids under 12 pay $8, seniors 65 and over pay $9, everyone else pays $14. A friend wrote:

if age < 12:
    price = 8
if age >= 65:
    price = 9
else:
    price = 14

What happens when a 10-year-old buys a ticket?