Python will automatically convert certain values to True and False if a boolean is needed in a conditional statement.
These values are said to be "Truthy" and "Falsy". They are not boolean values, but are converted automatically when needed. (You can convert them manually with the bool() command to see their Truthy and Falsy value.)
False
0 and 0.0
"" (the empty string)
empty collections (tuples, lists, dictionaries, etc.)
True
non-zero ints and floats
non-empty strings
non-empty collections
In Python you can use Truthy or Falsy values to write code that is cleaner. It may or may not be more readable.
For example:
If you want the code to run only when the user has children:
if(num_children > 0): becomes if(num_children):
If you want the code to run only if a list contains elements:
if(len(my_list) > 0): becomes if(my_list):
If you want the code to run only if a string is empty
if(len(name)== 0): or if(name == ""): becomes if(not name):
The or operator is a binary operator that must connect two booleans. Sometimes you wish to check if a variable takes one of several values, but you cannot use the or operator to connect two non-booleans, or it will convert to their boolean value.
WRONG
name = "Frank"
if(name == "John" or "Joe" or "Bobby"):
print(name)
else:
print("Name not included.")
This will print "Frank", because name == "John" is False but both "Joe" and "Bobby" are truthy, and the statement False or True or True returns True
RIGHT
name = "Frank"
if(name == "John" or
name == "Joe" or
name == "Bobby"):
print(name)
else:
print("Name not included.")
RIGHT (Recommended)
name = "Frank"
if(name in ["John", "Joe", "Bobby"]): #checks to see if name is in a list
print(name)
else:
print("Name not included.")