In this tutorial, you'll learn about the Python Boolean data type, how to use it, and how Python evaluates truthy and falsy values.
Introduction to Boolean Data Type
In programming, we often need to check conditions—whether something is true or false—to control the flow of the program.
Python provides a special data type called bool
that has only two values:
True
False
Note: These must start with capital
T
andF
respectively.
Example:
is_active = True
is_admin = False
These are boolean variables that hold either True
or False
.
Booleans in Comparisons
When you compare two values, the result is a boolean:
x = 20
y = 10
print(x > y) # True
print(x < y) # False
Comparison also works with strings:
x = 'a'
y = 'b'
print(x > y) # False
print(x < y) # True
The bool()
Function
You can check the truthiness of a value using the bool()
function:
print(bool('Hi')) # True
print(bool(100)) # True
print(bool(0)) # False
Truthy and Falsy Values
-
Truthy values are those that evaluate to
True
when passed tobool()
-
Falsy values evaluate to
False
Falsy values in Python include:
-
The number
0
-
An empty string
''
-
The value
False
-
The special value
None
-
An empty list
[]
-
An empty tuple
()
-
An empty dictionary
{}
Any other value is considered truthy.
Exercises
Exercise 1
Declare a variable is_student
and assign True
to it. Then print its value:
is_student = True
print(is_student)
Exercise 2
Compare two numbers using >
and <
and print the results:
a = 5
b = 10
print(a > b) # False
print(a < b) # True
Exercise 3
Use the bool()
function with different types of values:
print(bool(0)) # False
print(bool(42)) # True
print(bool('')) # False
print(bool('Python')) # True
Exercise 4
Write a small program that checks if a string is empty or not:
user_input = ''
if bool(user_input):
print("Input is not empty")
else:
print("Input is empty")
Summary
-
The Boolean data type in Python includes only
True
andFalse
-
You can use comparison operators and the
bool()
function to evaluate expressions -
Falsy values include
0
,''
,False
,None
,[]
,()
,{}
-
Any value not falsy is considered truthy
-
Booleans are fundamental for control flow and decision-making in Python
Practice comparing values and testing expressions with bool()
to master how Python evaluates truth and falsehood.
Copyright Statement: Unless stated otherwise, all articles are original to this site, please credit the source when sharing.
Article link:http://pybeginners.com/python-tutorial/python-boolean/
License Agreement:Attribution-NonCommercial 4.0 International License