A boolean has exactly two possible values: True and False. Booleans usually come from comparisons and logical expressions.
Comparison operators#
print(10 == 10) # True
print(10 != 10) # False
print(7 < 12) # True
print(7 >= 7) # True
print("a" < "b") # TrueImportant distinction:
=assigns a value.==compares two values.
Strings compare lexicographically by Unicode code point, which is case-sensitive: "Z" < "a" is True.
Logical operators#
age = 20
has_ticket = True
print(age >= 18 and has_ticket) # True
print(age < 13 or has_ticket) # True
print(not has_ticket) # Falseand is true only when both sides are true. or is true when at least one side is true. not reverses a boolean.
These operators short-circuit. In a and b, Python evaluates b only when a is truthy. In a or b, it evaluates b only when a is falsy.
name = ""
display = name or "Anonymous"
print(display) # AnonymousThis works because an empty string is falsy.
Truthiness#
Many values behave like False in a condition:
False,None- Numeric zero:
0,0.0 - Empty collections:
"",[],(),{},set()
Everything else is truthy by default.
items = [1, 2, 3]
if items:
print("The list is not empty")This is more idiomatic than if len(items) > 0, though both are correct.
Operators on strings and lists#
Some operators have non-mathematical meanings:
print("ab" * 3) # ababab
print("a" in "cat") # True
print([1, 2] + [3]) # [1, 2, 3]in tests membership. It is often clearer than a loop for simple checks.
Practice#
Predict the result of each expression, then verify in the compiler:
score = 84
passed = score >= 60
distinction = score >= 85
print(passed)
print(passed and distinction)
print(passed or distinction)
print(not passed)Next, use these conditions to control which code runs with if, elif, and else.
