In Python, a Boolean value represents one of two values: True or False. Booleans are typically used in conditional statements or comparisons to control the flow of a program.
, Python today has an explicit Boolean data type called bool, with the values True and False available as new preassigned built-in names. Internally, the names True and False are instances of bool
Note:- True and False behave exactly like the integers 1 and 0
There are only two Boolean values:
- True
- False
Booleans can be created in several ways:
1. Direct Assignment:
is_user_active = True
is_completed = False
2. Using Comparison Operators:
- ==: Checks if two values are equal.
- !=:Checks if two values are not equal.
- >:Greater than.
- <: Less than.
- >=: Greater than or equal to.
- <=: Less than or equal to.
Example:
a = 25
b = 30
print(a > b) # False
print(a == 5) # True
3. Using Logical Operators:
and: Returns True if both conditions are true.
or: Returns True if at least one condition is true.
not: Reverses the Boolean value.
Example:
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
What is Truthy and Falsy Values
In Python, many values can be implicitly converted to True or False in a Boolean context:
Falsy values: None, 0, 0.0, ‘ ‘ (empty string), [] (empty list), () (empty tuple), {} (empty dictionary).
Truthy values: Anything that is not considered falsy, like non-zero numbers, non-empty strings, and collections.
Example:
if []:
print("This won't be printed because an empty list is Falsy.")
else:
print("This will be printed.")