Booleans & Conditionals

Download notebook

Boolean expressions evaluate to True or False. Conditionals use those results to decide what code runs. Together, they let your program respond to different inputs and data.

Boolean Expressions

A boolean expression is a comparison that produces one of two values: True or False. In Python, both are capitalised.

You create boolean expressions with comparison operators. Note that == (double equals) checks equality, while = (single equals) assigns a value to a variable.

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to
3 == 3
True
5 != 3
True
7 > 10
False
4 <= 4
True

The result is a boolean value, which you can store in a variable like anything else:

result = 10 > 5
print(result)
True

Logical Operators

You can combine boolean expressions using and, or, and not:

Operator Returns True when… Example Result
and Both sides are True True and False False
or At least one side is True True or False True
not The expression is False not True False
(5 > 3) and (2 < 4)
True
(10 < 5) or (7 > 3)
True
not (8 == 8)
False

These become useful once you start combining them with conditionals.

Conditionals

Conditionals let your program take different paths depending on whether a condition is True or False.

Python uses if, elif, and else:

if condition:
    # runs if condition is True
elif another_condition:
    # runs if the first was False but this one is True
else:
    # runs if none of the above were True

You can chain as many elif blocks as you need. The else is optional but serves as a fallback.

CautionIndentation matters

The code inside each block must be indented (four spaces is standard). Python uses indentation to know which lines belong to which block. If your indentation is wrong, you’ll get an IndentationError. Also note the colon : at the end of each if, elif, and else line.

A basic example:

age = 40

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You must be at least 18 to vote.")
You are eligible to vote.

Putting It Together

Tipinput()

The following examples use the built-in input() function, which prompts the user to type something and returns it as a string. You’ll often need to convert the result using int() or float() before doing maths with it.

Multiple conditions with elif

age = input("Enter an age: ")
age = int(age)

if age < 18:
    print("You're eligible for a student discount!")
elif age >= 65:
    print("You're eligible for a senior discount!")
else:
    print("No discount available.")

Try a few different inputs to see how the if-elif-else branches work.

Combining with and

Check whether a restaurant is open based on the day and the hour:

day = input("Enter the day of the week: ")
day = day.lower()

hour = input("Enter the current hour (24-hour format): ")
hour = int(hour)

if (day != "sunday") and (hour >= 11) and (hour < 24):
    print("The restaurant is open.")
else:
    print("The restaurant is closed.")

Combining with or

Offer a discount if someone is a premium member or has a discount code:

is_premium = input("Are you a premium member? (yes/no): ").lower()
has_code = input("Do you have a discount code? (yes/no): ").lower()

if (is_premium == "yes") or (has_code == "yes"):
    print("You get a discount!")
else:
    print("No discount available.")

Using not

Check if a user is not old enough to enter:

age = input("Enter your age: ")
age = int(age)

if not (age >= 18):
    print("Access denied. You must be at least 18.")
else:
    print("Access granted.")

Challenges

1. Predict the Output

What will the following expressions evaluate to? Work through each one before running it in Python.

  • 10 > 5
  • 3 == 4
  • 6 <= 6
  • True and False
  • True or False
  • not (5 > 3)
  • (10 > 5) and (3 == 4)
print(10 > 5)                    # True
print(3 == 4)                    # False
print(6 <= 6)                    # True
print(True and False)            # False
print(True or False)             # True
print(not (5 > 3))              # False
print((10 > 5) and (3 == 4))    # False
True
False
True
False
True
False
False

2. Even or Odd

Write a program that checks if a number is even or odd. Hint: the modulo operator % gives the remainder after division.

num = 3

if num % 2 == 0:
    print("Even")
else:
    print("Odd")
Odd

3. Temperature Check

Write a program that takes a temperature and prints "It's moderate" if it’s between 15°C and 30°C, or "Too hot or cold for me!!" otherwise. Use and in your solution.

temp = input("Enter the temperature in Celsius: ")
temp = float(temp)

if temp >= 15 and temp < 30:
    print("It's moderate.")
else:
    print("Too hot or cold for me!!")

4. Traffic Light Simulator

Simulate a traffic light system where an input of:

  • “red” prints “Stop”
  • “yellow” prints “Slow down”
  • “green” prints “Go”
  • Any other input prints “Invalid color”
light = input("Enter traffic light color (red/yellow/green): ")
light = light.lower()

if light == "red":
    print("Stop")
elif light == "yellow":
    print("Slow down")
elif light == "green":
    print("Go")
else:
    print("Invalid color")