Booleans are one of the simplest and most powerful data types in Python. They represent two possible values: True
and False
. These values are used in conditional statements, loops, comparisons, and logic operations throughout any Python program.
Let’s explore the Boolean data type through examples and understand how they behave in different contexts.
Example 1: Assigning Boolean Values
is_python_fun = True
is_java_easy = False
print(is_python_fun)
print(is_java_easy)
Booleans can be directly assigned using the keywords True
and False
(note the capital T and F).
Example 2: Boolean from Comparison
result = 10 > 5
print(result)
Most often, Booleans are the result of comparison operations like greater than, less than, or equal to.
Example 3: Using Booleans in Conditions
logged_in = True
if logged_in:
print("Access granted")
Booleans are commonly used in if
statements to control the flow of your program.
Example 4: Boolean and Numbers
print(bool(0)) # False
print(bool(10)) # True
Python converts numbers to Booleans. Zero is treated as False
, any other number is True
.
Example 5: Boolean and Strings
print(bool("")) # False
print(bool("Hello")) # True
An empty string evaluates to False
, while any non-empty string evaluates to True
.
Example 6: Boolean from Expressions
a = 15
b = 20
print(a == b) # False
print(a != b) # True
Comparison expressions automatically return Boolean values depending on the condition.
Example 7: Logical AND
x = True
y = False
print(x and y)
The and
operator returns True
only if both values are True
.
Example 8: Logical OR
x = False
y = True
print(x or y)
The or
operator returns True
if at least one of the values is True
.
Example 9: Logical NOT
status = True
print(not status)
The not
operator inverts the Boolean value. If it's True
, it becomes False
, and vice versa.
Example 10: Combining Conditions
age = 25
country = "India"
if age > 18 and country == "India":
print("Eligible to vote")
You can combine multiple Boolean expressions using logical operators to build more complex conditions.
Summary
- Booleans represent two values:
True
andFalse
. - They are returned by comparison operations and used in conditions.
- Values like
0
,""
,None
, and empty collections evaluate toFalse
. - Logical operators
and
,or
, andnot
help combine or negate conditions.
Understanding Booleans is essential for decision-making in code. From simple conditions to complex logic, they form the backbone of control flow in any Python program.