Skip to main content
Back to module
Python Fundamentals · Getting Started

Conditions and booleans

Reading37mLesson 3 of 3 in this module

What you'll learn

  • Branch with if/elif/else
  • Compare values with the six comparison operators
  • Combine conditions with and, or and not
  • Order an elif chain so the first true branch is the right one

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

Why it matters

Programs become useful when they make decisions: flag a temperature that is too high, give a discount over a certain spend, reject a password that is too short, assign a letter grade. Every one of those is a condition: a question with a yes-or-no answer, followed by different code for each answer.

Booleans: True and False

A comparison produces a boolean, a value that is either True or False:

Python
print(5 > 3)      # True
print(5 == 3)     # False   (== asks "are these equal?")
print(5 != 3)     # True    (!= means "not equal")
print(4 <= 4)     # True
print("cat" == "Cat")   # False: comparisons are case-sensitive

The six comparison operators are ==, !=, <, <=, > and >=. Remember: a single = stores a value, a double == compares.

Combining conditions

Use and, or and not to build bigger questions:

Python
temp = 22
humidity = 70

print(temp > 18 and temp < 26)    # True: both parts are True
print(temp > 30 or humidity > 60) # True: at least one part is True
print(not temp > 30)              # True: flips False to True

Python also lets you chain comparisons the way you would in maths: 18 < temp < 26 means the same as temp > 18 and temp < 26.

if, elif and else

Python
temp = 31

if temp > 30:
    print("Too hot: open the vents")
elif temp < 10:
    print("Too cold: turn on the heater")
else:
    print("Temperature OK")

How it works:

  1. Python checks the if condition. If it is True, it runs that indented block and skips the rest.
  2. Otherwise it checks each elif ("else if") in order and runs the first one that is True.
  3. If none matched, the else block runs. elif and else are both optional.

Indentation is part of the syntax. The lines that belong to a branch are indented (four spaces is the standard). The colon at the end of the if line is required. When the indentation ends, so does the branch.

Order matters in elif chains

Because Python stops at the first true branch, put the most specific tests first:

Python
score = 95

# Wrong order: 95 is >= 60, so this prints "D"
if score >= 60:
    grade = "D"
elif score >= 90:
    grade = "A"

# Right order: highest threshold first
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(grade)   # A

Truthiness

if does not need a comparison. Python treats some values as "falsy": 0, 0.0, the empty string "", empty lists and None. Everything else is "truthy":

Python
name = ""
if name:
    print(f"Hello, {name}")
else:
    print("Please enter your name")

This is a neat shortcut for "is it empty?", but use explicit comparisons when they are clearer, such as if count == 0:.

What about input()?

In a terminal, input("Your age: ") pauses the program and returns what the user typed, always as a string, so you would write age = int(input("Your age: ")). The in-browser runner on this site cannot pause for typing, so in the Do tab we set values directly or pass them to a function. The decision logic is exactly the same.

A worked example

A theme park ride needs riders to be at least 120 cm tall, or at least 100 cm when riding with an adult:

Python
def can_ride(height_cm, with_adult):
    if height_cm >= 120:
        return True
    elif height_cm >= 100 and with_adult:
        return True
    else:
        return False

print(can_ride(130, False))  # True
print(can_ride(110, True))   # True
print(can_ride(110, False))  # False

def creates a function, a named, reusable block that takes inputs and returns a result. Module 2 covers functions properly; here it just lets us test one rule with several inputs. The whole rule also fits on one line: return height_cm >= 120 or (height_cm >= 100 and with_adult).

Common mistakes

  • = instead of ==. if temp = 30: is a SyntaxError.
  • Missing colon or indentation. Every if, elif and else line ends with : and its block is indented.
  • Testing in the wrong order. In an elif chain, the first true branch wins.
  • if x == 1 or 2: This is always true, because 2 on its own is truthy. Write if x == 1 or x == 2: or if x in (1, 2):.
  • Comparing text with numbers. "10" > 9 is an error. Convert first.

Quick recap

  • Comparisons (== != < <= > >=) give True or False.
  • and, or and not combine conditions.
  • if / elif / else runs the first branch whose condition is true.
  • Indentation and the colon define each branch.
  • Empty and zero values are falsy; most other values are truthy.

Try it

In the Do tab you will finish two functions: one turns a score into a letter grade, the other decides whether a reading is in a safe range.

Key terms (5)

boolean
A value that is either True or False, produced by comparisons.
comparison operators
The operators ==, !=, <, <=, > and >= that compare two values and give a boolean.
elif
Short for "else if": a further condition checked only when the conditions above it were false.
Indentation
The spaces at the start of a line, which in Python mark which lines belong to a branch or block.
falsy
Describes values that act as False in a condition, such as 0, 0.0, an empty string, an empty list and None.

Recap

  • Comparisons (== != < <= > >=) give True or False; a single = stores a value.
  • and, or and not combine conditions.
  • if / elif / else runs the first branch whose condition is true, so put the highest threshold first.
  • The colon and indentation define each branch.
  • Empty and zero values are falsy; most other values are truthy.
Also in this lesson: