HOME HTML EDITOR C JAVA PHP python

Python Booleans

In Python, a boolean represents one of two truth values: True or False (always capitalized). Booleans are essential for comparisons, decision-making with if statements, and loop conditions.

Boolean Values and Comparisons

Comparing values with operators such as >, <, ==, and != automatically evaluates to True or False:

is_logged_in = True
has_access = False

print(10 > 5)     # True
print(10 == 5)    # False
print(10 != 5)    # True
print(is_logged_in, has_access)

Evaluating Values with bool()

The bool() function converts any value into True or False. Most non-empty values are truthy, while empty containers, zero, and None are falsy:

print(bool("Python"))   # True
print(bool(100))        # True
print(bool(""))         # False (empty string)
print(bool(0))          # False (zero)
print(bool([]))         # False (empty list)
print(bool(None))       # False

Booleans in Conditional Statements

Conditions inside if statements use boolean logic to decide which block of code runs:

score = 82

if score >= 50:
    print("Passed!")
else:
    print("Try again.")
Tip: Remember that True and False must start with an uppercase T and F—true or false will raise a NameError.