Python Pop Quiz - Truthy or Falsey
Python supports Booleans in much the same way as other programming languages do. In Python’s case, it uses the True and False keywords. But there is also the concept of truthy and falsey. An example of a truthy value in Python is a number greater than zero (also a number less than zero), and an example of a falsey value would be an empty string. When used in a conditional expression or some functions, these values return True or False.
Why does this matter? Because you’ll write code where you need to know if a string is empty or not. You could check if a dictionary is empty or not too.
With that in mind, you are ready to try this chapter’s quiz!
The Quiz
What does the following code print out, if anything?
A) An exception
B) 1
C) 2
D) 3
E) None of the above
Hint
Did you know that a bool type in Python is a subclass of int?
The Answer
C) 2
Explanation
Python includes many different built-in functions. You can see two of these functions in this quiz:
sum()- takes an iterable, sums up the contents (if it can), and returns the totalall()- takes an iterable and returnsTrueif all the elements in the iterable are true andFalseotherwise.
Try running each of those all() functions that are inside the sum() function individually:
>>> all([[]])
False
>>> all([])
True
>>> all([[[]]])
TrueWhat’s going on here? To figure that out, you will look at each of these statements one at a time:
all([[]])returnsFalsebecause the passed in list has one element, an empty list[]. An empty list is falsey!all([])returnsTruebecause the iterable is empty. If you passed it an empty string, it would also returnTrue!all([[[]]])returnsTruebecause the passed single nested list contains something. In this case, it contains an empty list. But because it contains something, it now evaluates toTrue.
In Python, the bool data type is a subclass of int. That means that True maps to one and False maps to 0.
Look at that code again:
print(sum([
all([[]]),
all([]),
all([[[]]])
]))You can rewrite this code to use the return values you saw earlier:
print(sum([
False,
True,
True
]))Then you can rewrite it again even simpler:
print(sum([
0,
1,
1
]))What does 0 + 1 + 1 evaluate to? The number 2, of course!



