Booleans
In this tutorial, we'll represent yes/no values with True and False.
A boolean is a value that is either True or False.
is_raining = True
is_logged_in = False
Booleans are used when your program needs to make decisions.
Comparisons Create Booleans
Most booleans come from comparisons:
age = 17
print(age >= 18)
print(age < 18)
Output:
False
True
Python checks the comparison and gives a boolean result.
Using Booleans With if
Booleans are often used in if statements:
is_member = True
if is_member:
print("Discount applied")
else:
print("No discount")
The if branch runs when the condition is True.
Boolean Operators
Use and, or, and not to combine boolean logic:
age = 20
has_ticket = True
print(age >= 18 and has_ticket)
print(age >= 18 or has_ticket)
print(not has_ticket)
and requires both sides to be true. or requires at least one side to be true. not flips the value.
Truthy and Falsy
Some non-boolean values behave like booleans in conditions:
name = ""
if name:
print("Name entered")
else:
print("No name yet")
An empty string is falsy. A non-empty string is truthy.
Common Mistake
Booleans start with capital letters:
is_ready = True # correct
is_done = false # wrong
Python uses True and False, not true and false.
Practice
Create variables for age and has_permission. Print whether the person is allowed in if they are at least 13 and have permission.