True
and False
are two values python Boolean's hold. This is an built-in data types.
Boolean represent True or False about statement.
x = 5 y = 10 is_greater = x > y print(is_greater) # Output: False
There are three boolean operators in python.
and
: Both conditions must beTrue
or
: At least one condition must beTrue
.not
:Negates
the condition.
Python And :-
A | B | A AND B |
False | False | False |
False | True | False |
True | False | False |
True | True | True |
Here is simple example defining above
# Define two boolean variables x = True y = False # Using the AND operator result = x and y # Output the result print(result) # Output: False
Python Or :-
A | B | A AND B |
False | False | False |
False | True | True |
True | False | True |
True | True | True |
Example -
x = 5 y = 10 z = 3 # Using the OR operator result = (x < y) or (z > y) print(result) # Output: True
Python Not :-
Python not, reverses boolean value
A | not A |
True | False |
False | True |
Who's True or who's is not?
In Python, the following values evaluate to True in a boolean context:
Any non-zero numerical value (e.g., 1, 2, -3)
Any non-empty sequence or collection (e.g., [1, 2], "hello", (1,))
The special value True itself
Where as, the following values evaluate to False in a boolean context
The numerical value 0 (zero)
Empty sequences or collections (e.g., [], "", ())
The special value False itself
None
here are examples demonstrating truthiness and falseness in Python
# Examples of values evaluating to True print(bool(1)) # Output: True print(bool(3.14)) # Output: True print(bool(-5)) # Output: True print(bool([1, 2, 3])) # Output: True print(bool("hello")) # Output: True print(bool(True)) # Output: True # Examples of values evaluating to False print(bool(0)) # Output: False print(bool([])) # Output: False print(bool("")) # Output: False print(bool(())) # Output: False print(bool(False)) # Output: False print(bool(None)) # Output: False
Python bool()
function
The bool()
function can return a boolean value. This function can take various types of input and return True
or False
based on the truthiness of the input.
print(bool(0)) # Output: False print(bool(1)) # Output: True print(bool([])) # Output: False print(bool([1, 2, 3])) # Output: True print(bool("hello")) # Output: True print(bool("")) # Output: False print(bool(None)) # Output: False print(bool(True)) # Output: True
Note - It's important to remember that these are the basic rules, but certain objects can define their own truthiness in Python by implementing the __bool__
or __len__
methods.