Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Booleans

A boolean has only two possible values: True and False. Booleans are the answers to yes-or-no questions: is the password correct, is the list empty, is the number even? Every decision a program makes with if and every loop condition with while is a boolean, so they are at the heart of programming.

Comparisons give booleans

Comparing two values gives True or False:

age = 17
print(age >= 18)
print(age == 17, age != 17)
print("apple" < "banana")
print(3 < age < 20)
Output
False
True False
True
True

== checks whether two values are equal and != whether they differ. Do not confuse == (a question) with = (giving a variable a value). Strings compare in dictionary order, and Python lets you chain comparisons: 3 < age < 20 means 3 < age and age < 20.

and, or, not

Three operators combine booleans. and is True only when both sides are true, or when at least one side is true, and not turns True into False and the other way round:

has_ticket = True
is_adult = False
print(has_ticket and is_adult)
print(has_ticket or is_adult)
print(not is_adult)
print(has_ticket and not is_adult)
Output
False
True
True
True

Python stops working out and and or as soon as the answer is known: in a and b, if a is false, b is not even looked at. This is called short-circuit evaluation.

Truthy and falsy values

Any value can be used where a boolean is expected. Zero, empty strings, empty lists, empty dictionaries and None count as false; every other value counts as true:

for value in [0, 7, "", "hi", [], [0], None]:
    print(repr(value), "is", bool(value))
Output
0 is False
7 is True
'' is False
'hi' is True
[] is False
[0] is True
None is False

That is why you can write if name: to check that a name was typed, or if items: to check that a list is not empty. repr shows a value the way it is written in code, with quotes around strings.

Functions that answer yes or no

Many functions and methods return a boolean: isinstance(x, int), "abc".isalpha(), 5 in [1, 5, 9]. Your own functions can do the same with return x % 2 == 0.

Practice exercises

  1. Store a temperature and print whether it is below 0, between 0 and 30, or above 30, using comparisons.
  2. Print whether a year is a leap year: divisible by 4 and not by 100, or divisible by 400.
  3. Print bool of 0.0, " " (a space) and {} and explain each.
  4. Write an expression that is True when a number is between 1 and 10 or equal to 100.