Booleans and comparisons

Topic 1 of 3 in Making decisions6 min readBeginnerFree course

Overview

Programs make decisions: is the password correct? Is the basket empty? Is the user old enough? Each question has a yes-or-no answer, which Python represents with the boolean values True and False. This lesson covers how to ask those questions; the next one uses the answers to choose what to do.

True and False

Python
is_raining = True
has_umbrella = False
print(type(True))     # <class 'bool'>

Note the capital letters: True and False are keywords; true is just an undefined name.

Comparison operators

Operator Meaning Example Result
== equal to 3 == 3 True
!= not equal to 3 != 4 True
< less than 2 < 5 True
<= less than or equal 5 <= 5 True
> greater than 2 > 5 False
>= greater than or equal 18 >= 18 True
Python
age = 16
print(age >= 18)        # False
is_adult = age >= 18    # store the answer in a variable

= vs ==: one equals sign assigns, two compare. if age = 18: is a syntax error (Python helpfully suggests ==).

Comparing strings

Strings compare by characters, and the comparison is case-sensitive:

Python
"apple" == "apple"     # True
"Apple" == "apple"     # False
"apple" < "banana"     # True — alphabetical (by character code)
"Zebra" < "apple"      # True — all capitals come before lower case!

Normalise before comparing user input: answer.strip().lower() == "yes".

Chained comparisons

Python lets you write ranges the way you would in maths:

Python
0 <= score <= 100       # same as: 0 <= score and score <= 100
18 <= age < 65

Logical operators: and, or, not

Combine conditions:

Python
age >= 18 and has_ticket          # both must be True
is_weekend or is_holiday          # at least one must be True
not is_raining                    # flips True ↔ False
A B A and B A or B
True True True True
True False False True
False True False True
False False False False

Precedence: not is applied first, then and, then or. So:

Python
is_member or age < 12 and has_ticket
# means: is_member or (age < 12 and has_ticket)

Whenever you mix and and or, add brackets to make your intention explicit.

Short-circuiting

Python stops evaluating as soon as it knows the answer: in a and b, if a is False, b is never checked; in a or b, if a is True, b is skipped. That lets you guard risky checks:

Python
count != 0 and total / count > 10    # never divides by zero

Truthy and falsy

Any value can be used where a boolean is expected. Python treats some values as false and everything else as true:

Truthy and falsy values. Falsy — treated as False: False, None, 0 and 0.0, the empty string “”, and empty collections [] () {} set(). Truthy — everything else: True, numbers like 1, -5 and 3.14, non-empty strings like “hello” and even “ “ (a space), a list with one item such as [0], and any object by default.

Python
bool(0)        # False
bool(42)       # True
bool("")       # False
bool("hi")     # True
bool([])       # False

This makes some checks short and readable:

Python
name = input("Name: ").strip()
if name:                 # True if the user typed something
    print("Hello", name)

None

None is Python’s value for “nothing here” — for example a function that doesn’t return anything gives None. It’s falsy. To check for it specifically, use is:

Python
result = None
if result is None:
    print("No result yet")

(is checks whether two names refer to the very same object. Use it for None, True and False; use == for comparing values.)

Booleans are numbers too

True behaves like 1 and False like 0, so you can count Trues by adding them:

Python
answers_correct = [True, False, True, True]
print(sum(answers_correct))     # 3

Remember: == compares, = assigns; add brackets when mixing and and or; and empty or zero values are falsy.

Exercise

Ticket eligibility checks

A cinema has rules. Given age, has_student_card, is_member and title, compute and print five booleans: (1) is_adult — 18 or over; (2) gets_discount — under 12, OR 65 and over, OR a student with a card; (3) can_watch_15 — 15 or older; (4) free_popcorn — a member who is NOT a child (12 or over); (5) title_given — the title is not empty after stripping spaces (use truthiness, not len). Test with the values in the starter, then try changing them.

Python
age = 16
has_student_card = True
is_member = True
title = "  Inside Out 3 "

# 1. is_adult

# 2. gets_discount

# 3. can_watch_15

# 4. free_popcorn

# 5. title_given

print(is_adult, gets_discount, can_watch_15, free_popcorn, title_given)

Summary

  • A boolean is True or False; comparisons (==, !=, <, <=, >, >=) produce booleans.
  • = assigns, == compares — mixing them up is a classic bug.
  • Combine conditions with and, or and not; and binds tighter than or, so add brackets when mixing.
  • Comparisons can be chained: 0 <= x < 10.
  • Empty values, zero and None are falsy; almost everything else is truthy.