Booleans & Operators
Every decision a program makes comes down to a question with a yes or no answer. Is the cart total above ₹500? Is the user's age between 18 and 60? Is the PNR in the list? In Python, these answers are Booleans: the values True and False.
In this lesson you will create Booleans with comparison operators, combine them with and, or and not, learn which values Python treats as true or false, and meet the membership, identity, assignment and walrus operators.
Comparison operators
A comparison asks a question about two values and gives back True or False.
| Operator | Question | Example | Result |
|---|---|---|---|
== | Equal? | 5 == 5.0 | True |
!= | Not equal? | 3 != 3 | False |
< | Less than? | 17 < 18 | True |
> | Greater than? | 250 > 500 | False |
<= | Less than or equal? | 18 <= 18 | True |
>= | Greater than or equal? | 40 >= 33 | True |
Python also lets you chain comparisons, exactly as you would write them in maths:
age = 20
cart_total = 650
print(age >= 18)
print(18 <= age < 60)
print(cart_total > 500)
print("apple" < "banana", "Zebra" < "apple")True True True True True
18 <= age < 60 means "age is at least 18 and less than 60". Strings compare letter by letter in Unicode order, where all capital letters come before small letters. That is why "Zebra" < "apple" is True, which surprises many people when sorting names.
and, or, not
The logical operators combine Booleans:
a and bisTrueonly when both are true.a or bisTruewhen at least one is true.not aflipsTruetoFalseand back.
has_ticket = True
has_id = False
is_child = False
print(has_ticket and has_id)
print(has_ticket or has_id)
print(not is_child)
can_board = has_ticket and (has_id or is_child)
print("Can board:", can_board)False True True Can board: False
Python is lazy in a useful way: with and, if the left side is false, it does not even look at the right side, and with or, if the left side is true, it stops there. This is called short-circuit evaluation.
Truthy and falsy values
Python can treat any value as true or false, not only True and False. The rule is short. These values are falsy (they count as false):
FalseandNone- Zero:
0,0.0 - Empty collections:
"",[],(),{},set(),range(0)
Everything else is truthy. This lets you write if cart: instead of if len(cart) > 0:.
and and or actually return one of their operands, not always True or False. That gives a handy pattern for default values:
typed_name = ""
name = typed_name or "Guest"
print("Welcome,", name)
city = "Kochi"
print(city or "Unknown")
print(0 or 100, 3 and 5)Welcome, Guest Kochi 100 5
typed_name or "Guest" gives typed_name if it is truthy, otherwise "Guest". Be careful when 0 is a valid value, though: marks or 50 would replace a real score of 0 with 50.
Assignment operators
You already know =. Each arithmetic operator also has a short form that updates a variable in place:
| Short form | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 2 | x = x * 2 |
x /= 2 | x = x / 2 |
x //= 2 | x = x // 2 |
x %= 3 | x = x % 3 |
x **= 2 | x = x ** 2 |
These work for strings and lists too: message += "!" adds an exclamation mark to the end.
Membership and identity
in and not in check whether a value is inside a string, list or other collection. is and is not check whether two names refer to the same object in memory, which is a stricter question than ==.
stations = ["Rohtak", "Jind", "Bhiwani"]
print("Jind" in stations)
print("Panipat" not in stations)
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
result = None
print(result is None)True True True False True
a and b hold equal values but are two separate lists, so == is True and is is False. In everyday code, use is only to compare with None (and with True or False in rare cases). For everything else, use ==.
The walrus operator
The walrus operator := (it looks like a walrus's eyes and tusks) assigns a value inside an expression. It is useful when you want to calculate something, keep it, and test it at the same time.
marks = [45, 72, 88, 91, 67]
if (count := len(marks)) > 3:
print(f"{count} students, average {sum(marks) / count:.1f}")
words = ["pen", "notebook", "bag", "calculator"]
long_words = [w for w in words if (size := len(w)) > 5]
print(long_words, "last size checked:", size)5 students, average 72.6 ['notebook', 'calculator'] last size checked: 10
Without the walrus, you would write count = len(marks) on a line before the if. Both are fine. Use := when it makes the code clearer, and always put brackets around it, as shown. It also shines in while loops, which you will see in while Loops.
Operator precedence
When an expression has several operators, Python applies them in a fixed order, from highest to lowest priority:
**(power)-x(negative sign)*,/,//,%+,-- Comparisons:
==,!=,<,>,<=,>=,in,is notandor
So 2 + 3 * 4 is 14, and -2 ** 2 is -4 because the power happens before the minus sign. When in doubt, add brackets: they cost nothing and make your intention obvious.
Common mistakes
=instead of==in a condition.if age = 18:is aSyntaxError. Comparisons need==.if grade == "A" or "B":This is always true, because it means(grade == "A") or "B", and"B"is truthy. Writegrade == "A" or grade == "B", or better,grade in ("A", "B").- Using
isto compare numbers or strings.ischecks identity, not value, and can give different answers on different Python versions. Use==. - Using
orfor defaults when 0 is valid.count or 10turns a real0into10.
Key points
- Comparisons (
==,!=,<,>,<=,>=) returnTrueorFalseand can be chained. and,orandnotcombine conditions, and they stop as soon as the answer is known.False,None, zero and empty collections are falsy; everything else is truthy.x += 1and friends update a variable in place.inchecks membership;ischecks identity and is mainly used withNone.- The walrus operator
:=assigns inside an expression; use brackets around it.
Exercise
A cinema in Lucknow gives a discount when the customer is a student or a senior citizen (age 60 or more), but only on weekdays. Create the variables age = 65, is_student = False and day = "Tue". Using in with the tuple ("Sat", "Sun"), work out a Boolean is_weekday, then a Boolean gets_discount, and print both.
Show solution
age = 65
is_student = False
day = "Tue"
is_weekday = day not in ("Sat", "Sun")
gets_discount = is_weekday and (is_student or age >= 60)
print("Weekday:", is_weekday)
print("Discount:", gets_discount)Weekday: True Discount: True
The brackets make sure or is checked before and; without them, and would bind first and change the meaning.
Quick Quiz
1. What does 10 <= 15 < 20 evaluate to?
Chained comparisons work like maths: 15 is at least 10 and less than 20.
2. What is the value of "" or "Guest"?
An empty string is falsy, so or returns the right-hand value.
3. Why is if colour == "red" or "blue": a bug?
Python reads it as (colour == "red") or "blue", and a non-empty string is truthy.
4. What does the walrus operator := do?
(n := len(items)) > 3 stores the length in n and compares it in one step.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
