🟢 Booleans¶
1. Definition and Initialization¶
In Python, boolean is a type that has two values: True
and False
. They are often used in conditions and comparisons.
b1 = True
b2 = False
print(b1) # prints: True
print(b2) # prints: False
True False
2. Boolean Operations¶
Python provides the and
, or
, and not
operations for booleans.
t = True
f = False
print(t and f) # prints: False
print(t or f) # prints: True
print(not t) # prints: False
False True False
3. Comparisons¶
Comparisons often result in a boolean value.
print(5 == 5) # prints: True
print(5 != 5) # prints: False
print(5 > 3) # prints: True
print(5 < 3) # prints: False
True False True False
4. Type Conversion¶
You can convert other data types to booleans using the bool()
function. Most values are considered "truthy" (convert to True
) or "falsy" (convert to False
).
print(bool(1)) # prints: True
print(bool(0)) # prints: False
print(bool("abc")) # prints: True
print(bool("")) # prints: False
True False True False
Here, 1
is truthy and 0
is falsy. Non-empty strings are truthy and empty strings are falsy.
5. is vs. ==¶
is
checks if both the variables point to the same object whereas ==
checks if the values for the two variables are the same. Here is an example:
list1 = []
list2 = []
list3=list1
print(list1 == list2) # prints: True
print(list1 is list2) # prints: False
print(list1 is list3) # prints: True
True False True
Even though list1
and list2
are empty lists, they are different objects. However, list1
and list3
are pointing to the same object.
6. None
Type¶
In addition to True
and False
, Python has a special type None
, which represents the absence of a value or a null value.
x = None
print(x) # prints: None
print(x is None)# prints: True
None True