Python Booleans ☯️
True or False?
Booleans represent one of two values: True or False. In programming, you often need to know if an expression is True or False to make decisions.
💡 Analogy: The Light Switch
A Boolean is like a light switch. It can only be in one of two states: ON (True) or OFF (False). There is no "halfway" or "maybe".
✨ Evaluating Expressions
When you compare two values, the expression is evaluated and Python returns the Boolean answer:
print(10 > 9) # True
print(10 == 9) # False
print(10 < 9) # False✅ Truthy Values
Almost any value is evaluated to True if it has some sort of content.
- Any string is True, except empty strings.
- Any number is True, except 0.
- Any list, tuple, set, and dictionary are True, except empty ones.
bool("abc") # True
bool(123) # True
bool(["apple"]) # True❌ Falsy Values
There are not many values that evaluate to False, except empty values, such as (), [], , "", the number 0, and the value None.
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})🎯 Real-World Application: Feature Flags
Companies like Facebook use Booleans to turn features on or off for specific users.
is_dark_mode_enabled = True
if is_dark_mode_enabled:
print("Applying dark theme...")
else:
print("Applying light theme...")🧠 Functions can Return a Boolean
You can create functions that return a Boolean Value:
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")💡 Did You Know? isinstance()
Python has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:
x = 200
print(isinstance(x, int)) # True