Python Booleans
1Python Booleans: overview
A boolean (bool) is a value that is either True or False, produced by comparisons and combined with and, or and not to make decisions in code.
Before this lesson: Python Data Types, Python Operators
2Python Booleans: diagram
3Python Booleans: explained step by step
A boolean is the simplest value there is: it is either True or False. Python's type for it is bool. Booleans are the answers to yes/no questions, and they are what if statements and loops use to decide what happens next.
Both names start with a capital letter. true and false are not Python; they are just undefined names and cause a NameError.
Comparisons produce booleans
Every comparison operator (==, !=, <, >, <=, >=) and the membership test in evaluates to a bool. You rarely type True yourself; you let a comparison create it.
age = 17
print(age >= 18)
print(age != 20)
print("a" in "banana")
print(type(age >= 18))
can_vote = age >= 18
print(can_vote)Storing a comparison in a variable such as can_vote gives the condition a name, which makes later code read like English.
bool is a kind of int
Surprising but useful: True is 1 and False is 0. bool is a subclass of int, so booleans work in arithmetic. The most practical trick is counting: add up a list of booleans to count how many are True.
print(True + True)
print(True * 10)
print(isinstance(True, int))
scores = [45, 80, 92, 38, 71]
passed = sum(score >= 50 for score in scores)
print("Passed:", passed)If you need to know whether something is specifically a boolean and not just a number, use isinstance(x, bool). Check for bool first, because isinstance(True, int) is also true.
and, or and not
Three keywords combine booleans. and needs both sides true, or needs at least one, and not flips the value. The logical conditions page shows how to build longer conditions, and operators lists their precedence: not first, then and, then or.
logged_in = True
is_admin = False
print(logged_in and is_admin)
print(logged_in or is_admin)
print(not is_admin)and / or return an operand, not just True or False
This detail trips up many learners. and and or short-circuit: they stop as soon as the answer is known, and the value they return is the operand that decided it, not necessarily a bool.
a or breturnsaifais truthy, otherwiseb.a and breturnsaifais falsy, otherwiseb.
username = ""
print(username or "Guest")
print(0 and 100)
print("Asha" and "Welcome")
items = []
print(len(items) > 0 and items[0])The last line is why short-circuiting is useful: when the list is empty, items[0] is never evaluated, so no IndexError happens. The idea of "which values count as false" is covered on the truthy and falsy page.
Chained comparisons
Python lets you write a range check the way you would on paper. 1 < x < 10 means 1 < x and x < 10, and x is only evaluated once.
x = 7
print(1 < x < 10)
print(10 <= x <= 20)
print(0 < x != 5)== versus is
== asks "are these values equal?" while is asks "are these the very same object?" Because True and False each exist only once, is True works for real booleans, but it is stricter than most code needs. Note that 1 == True is True, yet 1 is True is False.
flag = 1
print(flag == True)
print(flag is True)
is_ready = True
if is_ready:
print("go")The plain if is_ready: is the idiomatic form. Writing if is_ready == True: adds nothing and breaks for truthy values that are not exactly True.
Booleans as flags, and naming them well
A flag is a boolean variable that remembers whether something has happened, such as found = False before a loop and found = True inside it. Start names with is_, has_, can_ or should_ so the variable reads like a question: is_empty, has_discount. For checking many conditions at once, see any() and all(): all(flags) is true when every item is true, and any(flags) when at least one is.
Converting other values into booleans is covered in Python casting; the short version is that bool(x) follows the same rules an if does.
Quick reference: Python Booleans
- Python is vs == Operator: What Is the Difference? — `==` checks whether two objects have **equal values**, while `is` checks whether they are the **exact same ob…
4Python Booleans: syntax
is_ready = True # bool literals are capitalised
result = age >= 18 # comparisons give True/False
a and b a or b not a # combine conditions
1 < x < 10 # chained comparison
isinstance(x, bool) # is it really a bool?
sum(flags) # count the True values
5Python Booleans: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
cart_total = 85.0
is_member = True
has_coupon = False
items_in_cart = 4
free_shipping = cart_total >= 100 or is_member
big_order = 3 <= items_in_cart <= 10
gets_gift = free_shipping and big_order and not has_coupon
print("Free shipping:", free_shipping)
print("Big order:", big_order)
print("Gift:", gets_gift)
print("Greeting:", "" or "Welcome back")
print("Checks passed:", free_shipping + big_order + gets_gift)Expected outputFree shipping: True
Big order: True
Gift: True
Greeting: Welcome back
Checks passed: 3
7Python Booleans: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1-4Plain data: a number, two booleans written by hand, and an item count.
- Line 6
cart_total >= 100isFalse, butis_memberisTrue, soormakesfree_shippingTrue. - Line 7A chained comparison checks that
items_in_cartis between 3 and 10 inclusive:True. - Line 8
not has_couponisTrue, so all three parts of theandchain are true andgets_giftisTrue. - Line 10-12Printing each named boolean makes the program's decisions easy to follow.
- Line 13
""is falsy, soorreturns the right-hand operand: the text"Welcome back", not a bool. - Line 14Booleans are integers, so adding them counts the Trues:
True + True + Trueis3.
8Python Booleans: common mistakes
Using = instead of == in a condition
✗ Wrong
score = 10
if score = 10:
print("perfect")✓ Right
score = 10
if score == 10:
print("perfect")A single = assigns a value. Use == to compare two values.
Thinking the text "False" is False
✗ Wrong
enabled = "False"
if enabled:
print("feature on")✓ Right
enabled = "False"
if enabled.lower() == "true":
print("feature on")
else:
print("feature off")Compare the text to what you expect, or convert it properly with enabled.lower() == "true".
Writing or with a bare string
✗ Wrong
color = "green"
if color == "red" or "blue":
print("warm or cool")✓ Right
color = "green"
if color in ("red", "blue"):
print("warm or cool")Each side of or is a separate condition. Compare both, or use in.
Comparing a collection with == True
✗ Wrong
items = [1, 2]
if items == True:
print("has items")✓ Right
items = [1, 2]
if items:
print("has items")Just use the value as the condition. Non-empty lists are truthy.
Using is True for a number
✗ Wrong
flag = 1
if flag is True:
print("on")✓ Right
flag = 1
if flag:
print("on")is checks identity, not value. Use if flag: for truthiness, or flag == 1 for the number.
9Python Booleans: exercises
Write your answer, then press Check. The checks run in your browser.
1. Club entry check
Write code Easy ✓ CompletedWrite a function can_enter(age, has_ticket) that returns True only when the person is 18 or older and has a ticket. Return a real boolean, do not print.
def can_enter(age, has_ticket):
pass
and and return the result directly.def can_enter(age, has_ticket):
return age >= 18 and has_ticket
2. Predict the booleans
Predict the output Easy ✓ CompletedType exactly what this program prints. Think about what or and and return, and how True behaves as a number.
x = 1
print(True + True + False)
print(5 > 3 > 1)
print("" or "guest")
print(0 and 10)
print(not 0)
print(x == True, x is True)2
True
guest
0
True
True False
2 more exercises → 6 more examples
Questions learners ask
Why does 'or' sometimes return a string instead of True?
and/or return one of their operands, not a converted bool. "" or "Guest" returns "Guest" because the empty string is falsy. Wrap the expression in bool(...) if you specifically need True or False.
Should I write if x == True or just if x?
Write if x:. It is shorter, reads naturally with names like is_ready, and works for any truthy value. x == True fails for values such as 2 or a non-empty list, and x is True fails for 1. See truthy and falsy values.
Why is True + True equal to 2?
bool is a subclass of int, with True equal to 1 and False equal to 0. That is why you can add booleans and use sum() to count how many conditions are true.
Further reading
10Next lesson
Up nextPython OperatorsOperators are symbols such as +, == and and that combine values into a new value — a number from arithmetic, or True/Fa…Related:
Python OperatorsPython if, elif and elsePython Logical ConditionsPython Truthy and Falsy Values
← Python Casting · All Python Basics lessons · Practise in the IDE