Boolean Types in Python
What is a Boolean?
A Boolean is a data type that has only two possible values:
True
— represents truthFalse
— represents falsehood
Booleans are commonly used in conditions, comparisons, and controlling the flow of a program.
Boolean Values
In Python, True
and False
are special constants (keywords) and must be capitalized exactly as shown.
Example:
is_sunny = True
is_raining = False
print(is_sunny) # Output: True
print(is_raining) # Output: False
Boolean Expressions
Boolean values often result from expressions using comparison operators:
a = 10
b = 20
print(a > b) # False
print(a < b) # True
print(a == 10) # True
print(a != b) # True
Using Boolean Values in Conditions
Booleans are used in control flow statements like if
, while
:
is_logged_in = True
if is_logged_in:
print("Welcome back!")
else:
print("Please log in.")
Output:
Welcome back!
Boolean Operators
Python has three logical operators to combine or invert boolean values:
Operator | Description | Example | Result |
---|---|---|---|
and |
Logical AND | True and False |
False |
or |
Logical OR | True or False |
True |
not |
Logical NOT | not True |
False |
Example:
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
Truthy and Falsy Values
Besides True
and False
, other values are implicitly considered Boolean in conditions:
-
Values considered False in Python include:
False
,None
,0
,0.0
,""
(empty string),[]
(empty list),{}
(empty dict),set()
,()
(empty tuple) -
All other values are considered True
Example:
if 0:
print("This won't print")
else:
print("0 is considered False")
if "hello":
print("Non-empty string is True")
Output:
0 is considered False
Non-empty string is True
Converting to Boolean with bool()
You can convert any value to a Boolean using the bool()
function:
print(bool(0)) # False
print(bool(42)) # True
print(bool("")) # False
print(bool("Python")) # True
print(bool([])) # False
print(bool([1, 2])) # True
Summary
- Boolean values in Python are
True
andFalse
. - Result from logical expressions or can be assigned directly.
- Used in conditions, loops, and logical operations.
- Logical operators:
and
,or
,not
. - Many values have implicit Boolean context (truthy or falsy).
- Use
bool()
to convert values to Boolean explicitly.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.