3 == 3True
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.
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 toThe result is a boolean value, which you can store in a variable like anything else:
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 |
These become useful once you start combining them with conditionals.
Conditionals let your program take different paths depending on whether a condition is True or False.
Python uses if, elif, and else:
You can chain as many elif blocks as you need. The else is optional but serves as a fallback.
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:
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.
elifTry a few different inputs to see how the if-elif-else branches work.
andCheck whether a restaurant is open based on the day and the hour:
orOffer a discount if someone is a premium member or has a discount code:
notCheck if a user is not old enough to enter:
What will the following expressions evaluate to? Work through each one before running it in Python.
10 > 53 == 46 <= 6True and FalseTrue or Falsenot (5 > 3)(10 > 5) and (3 == 4)Write a program that checks if a number is even or odd. Hint: the modulo operator % gives the remainder after division.
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.
Simulate a traffic light system where an input of: