Python Booleans · Examples
Beginner

Python Booleans Examples

Short, runnable programs that show python booleans in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Booleans lesson.

1Validating a password

Each rule is a boolean with a name; combining them with and keeps the final check readable.

Validating a password
password = "Sunny2024"
long_enough = len(password) >= 8
has_digit = any(ch.isdigit() for ch in password)
has_upper = password != password.lower()
valid = long_enough and has_digit and has_upper
print(long_enough, has_digit, has_upper)
print("Valid:", valid)
Expected outputTrue True True
Valid: True

2Default values with or

or returns the first truthy operand, so it can supply a fallback for empty input.

Default values with or
nickname = ""
display = nickname or "Anonymous"
print("Hello,", display)
nickname = "Ravi"
print("Hello,", nickname or "Anonymous")
Expected outputHello, Anonymous
Hello, Ravi

3Counting with True and False

Because True is 1, sum() over a list of comparisons counts matches.

Counting with True and False
temps = [18, 25, 31, 22, 35, 29]
hot_days = sum(t > 28 for t in temps)
print("Hot days:", hot_days)
print("Share hot:", round(hot_days / len(temps), 2))
Expected outputHot days: 3
Share hot: 0.5

4A flag set inside a loop

Start with found = False and flip it when the search succeeds.

A flag set inside a loop
names = ["Maya", "Leo", "Zoe"]
found = False
for name in names:
    if name.startswith("L"):
        found = True
        print("Found:", name)
        break
print("Any name with L:", found)
Expected outputFound: Leo
Any name with L: True

5Short-circuit protects against errors

The right side of and only runs when the left side is true, so division by zero is avoided.

Short-circuit protects against errors
visits = 0
conversions = 5
rate_ok = visits > 0 and conversions / visits > 0.1
print(rate_ok)
visits = 20
print(visits > 0 and conversions / visits > 0.1)
Expected outputFalse
True

6Range check with a chained comparison

A chained comparison reads like a maths inequality and keeps the code short.

Range check with a chained comparison
readings = [4, 12, 37, 61, 99]
for value in readings:
    ok = 10 <= value <= 60
    print(value, "in range" if ok else "out of range")
Expected output4 out of range
12 in range
37 in range
61 out of range
99 out of range

Practise next

Python Booleans exercises → Back to the lesson

Python Operators examplesPython if, elif and else examplesPython Logical Conditions examplesPython Truthy and Falsy Values examples