0%

14- Booleans in Python

True or False. Yes or No. On or Off. Booleans are the simplest data type in Python, but they power every decision your program makes.

Every decision in programming comes down to a single question: is this true or false? Is the user logged in? True or False. Is the score high enough to win? True or False. Is the file still open? True or False. Booleans are the answer to these questions. They have only two possible values: True and False. That is it. Two little words that control the flow of every program you will ever write. Booleans are named after George Boole, a mathematician who developed Boolean algebra. This algebra became the foundation of modern computer science.

🕯️ Magic Note

In Python, True and False are written with capital first letters. true and false (lowercase) are not valid. This is a common beginner mistake. Remember: capital T and capital F.

Creating Booleans
You can create booleans directly by assigning True or False. Or you can get them as the result of comparison operations.

Python

# Direct assignment

is_logged_in = True

is_closed = False

is_magical = True

# From comparisons

x = 10

y = 20

is_greater = x > y # False

is_equal = x == y # False

is_less = x < y # True

# From other expressions

has_items = bool([]) # False (empty list is falsy)

has_name = bool(“hello”) # True (non-empty string is truthy)

💡 Use the bool() constructor to convert other values to booleans. This is useful for understanding what Python considers truthy or falsy.
Comparison Operators (Return Booleans)
Comparison operators always return a boolean value. They are the foundation of decision-making in Python.
OperatorMeaningExample (x=5, y=10)Result
==Equal tox == yFalse
!=Not equal tox != yTrue
>Greater thanx > yFalse
<Less thanx < yTrue
>=Greater than or equal tox >= yFalse
<=Less than or equal tox <= yTrue

Python

# Comparison operators in action

age = 25

print(age == 25) # True

print(age != 30) # True

print(age > 18) # True

print(age < 21) # False

print(age >= 25) # True

print(age <= 20) # False

# Compare strings (lexicographical order)

print(“apple” < “banana”) # True (‘a’ comes before ‘b’)

print(“cat” == “Cat”) # False (case sensitive)

⚠️ Do not confuse = (assignment) with == (comparison). x = 5 assigns the value 5 to x. x == 5 checks if x equals 5 and returns a boolean. This is one of the most common errors in programming.
Logical Operators (Combining Booleans)
Logical operators combine boolean values to create more complex conditions. They are essential for decision-making.
OperatorWhat It DoesExample (a=True, b=False)Result
andTrue only if BOTH are Truea and bFalse
orTrue if AT LEAST ONE is Truea or bTrue
notReverses the value (True becomes False)not aFalse

Python

is_weekend = True

has_time = False

# AND – both must be True

can_rest = is_weekend and has_time

print(can_rest) # False (has_time is False)

# OR – at least one must be True

can_go_out = is_weekend or has_time

print(can_go_out) # True (is_weekend is True)

# NOT – reverses the value

is_weekday = not is_weekend

print(is_weekday) # False

🕯️ Magic Note

The and and or operators short-circuit. For and, if the first value is False, Python does not even evaluate the second. For or, if the first value is True, Python skips the second. This can improve performance and prevent errors.

Python

# Short-circuit example

def risky_operation():

print(“This won’t run if short-circuited”)

return True

result = False and risky_operation() # risky_operation() never runs

print(result) # False

result = True or risky_operation() # risky_operation() never runs

print(result) # True

Truthy and Falsy Values
In Python, every value can be treated as a boolean in a condition. This is called truthiness. Some values are considered falsy (act like False), others are truthy (act like True).
Falsy Values (Act like False)Truthy Values (Act like True)
NoneAny non-None value
FalseTrue
0 (zero as int or float)Any non-zero number (1, -1, 3.14, etc.)
“” (empty string)Any non-empty string (“hello”, “0”, “False”)
[] (empty list)Any non-empty list ([1, 2, 3])
{ } (empty dictionary)Any non-empty dictionary ({“a”: 1})
set() (empty set)Any non-empty set ({1, 2, 3})
() (empty tuple)Any non-empty tuple ((1, 2))

Python

# Truthy and falsy in action

name = “”

if name:

print(f”Hello, {name}”)

else:

print(“Name is empty”) # This runs because empty string is falsy

count = 5

if count:

print(“We have items”) # This runs because 5 is truthy

items = []

if not items:

print(“The list is empty”) # This runs because empty list is falsy

💡 Using truthiness makes your code cleaner. Instead of if len(my_list) > 0:, just write if my_list:. Instead of if name != “”:, just write if name:. This is more Pythonic.
Booleans in Conditions (if Statements)
Booleans are the heart of conditional statements. The if statement executes code only when its condition is True.

Python

age = 18

has_permission = True

# Simple condition

if age >= 18:

print(“You are an adult”)

# Condition with and

if age >= 18 and has_permission:

print(“You can enter”)

# Condition with or

if age >= 18 or has_permission:

print(“At least one condition is true”)

# Condition with not

if not has_permission:

print(“Permission denied”)

Booleans in While Loops
While loops continue as long as their condition remains True. The condition is checked before each iteration.

Python

counter = 0

is_running = True

# Loop until a condition becomes False

while counter < 5:

print(f”Count: {counter}”)

counter += 1

# Using a boolean flag

attempts = 0

while is_running and attempts < 3:

print(“Trying…”)

attempts += 1

if attempts == 2:

is_running = False # This will end the loop next check

The bool() Constructor
Use bool() to explicitly convert a value to a boolean. This is useful for understanding or documenting truthiness.

Python

print(bool(0)) # False

print(bool(42)) # True

print(bool(“”)) # False

print(bool(“hello”)) # True

print(bool([])) # False

print(bool([1,2])) # True

print(bool(None)) # False

print(bool(True)) # True

Booleans Are Integers (Subclass of int)
In Python, True is actually a subclass of int with the value 1, and False has the value 0. This means you can use booleans in arithmetic.

Python

# Booleans as numbers

print(True + True) # 2 (1 + 1)

print(True + False) # 1 (1 + 0)

print(False * 10) # 0

print(True – 1) # 0

# Counting True values in a list

results = [True, False, True, True, False]

print(sum(results)) # 3 (number of True values)

# But be careful – this is a quirk, not a feature to rely on heavily

⚠️ Using booleans as numbers works, but it can make your code confusing. Avoid True + True in production code. Use clear logic instead. The fact that booleans are integers is an implementation detail, not something to exploit.
Common Mistakes with Booleans
  • Writing true or false (lowercase) instead of True or False (NameError)
  • Using = instead of == in conditions: if x = 5: (SyntaxError)
  • Forgetting truthiness: if my_list == True instead of if my_list
  • Comparing to True or False unnecessarily: if is_ready == True should be if is_ready
  • Confusing and / or logic with everyday English
Check Your Understanding
  • What are the two boolean values in Python?
  • What is the difference between = and ==?
  • Which values are considered falsy in Python? Name at least four.
  • What is the output of bool([]) and bool(“False”)?
  • Write an if statement that checks if a number is between 10 and 20.
  • What does short-circuiting mean for and and or?

⚡ Whisper

True and False. Two simple words. Two opposite whispers. Yet every decision your program makes, from the simplest to the most complex, comes down to choosing between them. Is the door open? Is the key correct? Is the time right? Each question becomes a boolean. Each boolean leads to a path. The program walks forward, choosing left or right, up or down, action or silence, all guided by these tiny torches of truth. Learn to love them. They are not just data. They are the breath of logic. The pulse of choice. The whisper that says “this way” or “not this way.” Without them, your code cannot decide. With them, it becomes alive with purpose.

Related posts