Python Booleans
Booleans have two possible values which is, True or False.
Boolean Values
It's common in programming to need to know whether an expression is True
or False
.
In Python, you can evaluate a certain expression and receive one of two results: True
or False
.
Example 1 :- Compare two values by evaluating the expression and by returning the boolean answer to Python :
print(10 > 9)
print(10 == 9)
print(10 < 9)
Output :-
False
False
Python will return True
or False
if you have a condition in a statement if
:
Example 2 :- Depending on whether the condition is True
or False
, print the following message :
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output :-
Evaluate Values and Variables
You can evaluate any value by using the bool()
function and return True
or False
.
Example 1 :- Evaluate a string and a number :
print(bool("Hello"))
print(bool(15))
Output :-
True
Example 2 :- Evaluate two variables :
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Output :-
True
Related Links
Most Values are True
If you have some sort of content, almost every value is evaluated to True
.
Every string, except empty strings, is True
.
Any number is True
, except 0
.
Except for empty lists, tuples, sets and dictionaries, all are True
.
Example :- The following will return True :
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
Output :-
True
True
Some Values are False
In fact, with the exclusion of empty values (for instance ()
, []
, {}
, ""
number 0 and value None), False does not value many values. And False
value is of course False
value.
Example 1 :- The following will return False :
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))
Output :-
False
False
False
False
False
False
Related Links
Functions can Return a Boolean
The functions you can create can return a boolean value :
Example 1 :- Print the answer of a function :
def myFunction() :
return True
print(myFunction())
Output :-
You can run code based on a function's Boolean result :
Python has also many incorporated functions, such as the isinstance()
function, that can be employed to determine if an object is of a certain type of data :
Example 2 :- Check if an object is an integer or not :
x = 200
print(isinstance(x, int))
Output :-