Monday, May 18, 2020

Booleans

Booleans



The built-in bool() function returns True or False. You can also use the if else conditional compound statement to take actions based on whether something evaluates as True or False. The capitalization of True and False is required.

if x op y:
    code here
else:
    other code here

where op is a relational or logical operator, such as >, <,  ==, etc.

It turns out you can also do math and string operations inside the argument of a call to bool()

print(bool(5-5))           #  False
print(bool("" + ""))     #  False
print(bool(0))              #  False

 A tuple or a list of empty strings actually evaluates to true.

t = ("", "", '')

print(bool(t)) #  True

 Here are all of the False return generating values in Python



()   [ ]  {}   ""   ''   0    None    False



There are still two more cases when you could use Python and get True or False values.


The one case would be in a class containing the  __len__ member function returning 0 or False. A bool() with that function as its argument will return False.


Finally the isinstance() built-in function checks if an object has a particular data type or not; it returns a True or False.

isinstance(var_name, data_type)

No comments:

Post a Comment