Understanding Python Booleans
A clear guide to Python Booleans for beginners
Python Booleans: True or False
In Python, a Boolean is a data type that represents two values: True
or False
. They’re especially useful in programming for evaluating conditions and controlling the flow of code.
Boolean Values
What is a Boolean?
A Boolean is simply a value that’s either True
or False
. In programming, these values are used to check if conditions are met.
Boolean Expressions
A Boolean expression evaluates a condition and returns either True
or False
. Here are some examples:
print(10 > 9) # True
print(10 == 9) # False
print(10 < 9) # False
Using Booleans in if Statements
We often use Boolean values in if statements to decide what code should run based on whether a condition is True or False.
Example: Checking Conditions with Booleans
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a") # This will print
Evaluating Values with bool()
Python has a built-in bool() function that can convert any value to a Boolean. The result will be True or False based on the value’s content.
Example: Using bool() to Evaluate Values
print(bool("Hello")) # True
print(bool(15)) # True
Example: Using bool() on Variables
x = "Hello"
y = 15
print(bool(x)) # True
print(bool(y)) # True
Which Values Are True?
Most values in Python evaluate to True. This includes:
- Any non-empty string, like "abc"
- Any non-zero number, like 123
- Any non-empty list, tuple, set, or dictionary
Example: Values That Return True
print(bool("abc")) # True
print(bool(123)) # True
print(bool(["apple", "cherry"])) # True
Which Values Are False?
Some values in Python evaluate to False, including:
- Empty values like "", [], , ()
- The number 0
- The value None
- The Boolean False itself
Example: Values That Return False
print(bool(False)) # False
print(bool(None)) # False
print(bool(0)) # False
print(bool("")) # False
print(bool(())) # False
print(bool([])) # False
print(bool({})) # False
Boolean Functions in Python
You can write functions that return a Boolean value. This is useful for making decisions based on conditions within a function.
Example: Simple Boolean Function
def my_function():
return True
print(my_function()) # True
You can also use this returned Boolean value in an if statement:
def my_function():
return True
if my_function():
print("YES!") # This will print "YES!" because my_function() returns True
else:
print("NO!")
Built-in Functions That Return Booleans
Python has many built-in functions that return a Boolean. One of the most commonly used is isinstance(), which checks if an object is of a specific type.
Example: Using isinstance() to Check Data Types
x = 200
print(isinstance(x, int)) # True, because x is an integer
Understanding Booleans is essential in Python, as they’re the basis for making decisions in your code. Try experimenting with different values and conditions to see how they evaluate to True or False!