Booleans & Operators

Python · Lesson 12 of 56 6 min read Updated

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.

OperatorQuestionExampleResult
==Equal?5 == 5.0True
!=Not equal?3 != 3False
<Less than?17 < 18True
>Greater than?250 > 500False
<=Less than or equal?18 <= 18True
>=Greater than or equal?40 >= 33True

Python also lets you chain comparisons, exactly as you would write them in maths:

PythonRun it yourself
age = 20
cart_total = 650

print(age >= 18)
print(18 <= age < 60)
print(cart_total > 500)
print("apple" < "banana", "Zebra" < "apple")
Output
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 b is True only when both are true.
  • a or b is True when at least one is true.
  • not a flips True to False and back.
PythonRun it yourself
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)
Output
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):

  • False and None
  • 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:

PythonRun it yourself
typed_name = ""
name = typed_name or "Guest"
print("Welcome,", name)

city = "Kochi"
print(city or "Unknown")
print(0 or 100, 3 and 5)
Output
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 formSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 2x = x * 2
x /= 2x = x / 2
x //= 2x = x // 2
x %= 3x = x % 3
x **= 2x = 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 ==.

PythonRun it yourself
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)
Output
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.

PythonRun it yourself
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)
Output
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:

  1. ** (power)
  2. -x (negative sign)
  3. *, /, //, %
  4. +, -
  5. Comparisons: ==, !=, <, >, <=, >=, in, is
  6. not
  7. and
  8. or

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 a SyntaxError. Comparisons need ==.
  • if grade == "A" or "B": This is always true, because it means (grade == "A") or "B", and "B" is truthy. Write grade == "A" or grade == "B", or better, grade in ("A", "B").
  • Using is to compare numbers or strings. is checks identity, not value, and can give different answers on different Python versions. Use ==.
  • Using or for defaults when 0 is valid. count or 10 turns a real 0 into 10.

Key points

  • Comparisons (==, !=, <, >, <=, >=) return True or False and can be chained.
  • and, or and not combine conditions, and they stop as soon as the answer is known.
  • False, None, zero and empty collections are falsy; everything else is truthy.
  • x += 1 and friends update a variable in place.
  • in checks membership; is checks identity and is mainly used with None.
  • 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
Python
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)
Output
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?

2. What is the value of "" or "Guest"?

3. Why is if colour == "red" or "blue": a bug?

4. What does the walrus operator := do?

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