True or False? bool() and truthiness
🌍 In real life. Ask "is there anything in this glass?" A glass with juice: yes. A glass with even one drop of water: still yes. Only an empty glass gets a no. And a wallet with zero taka in it is, for spending, the same as no money at all.
Python asks the same kind of question about any value.
The idea in one sentence: bool() turns any value into True or False: empty or zero is False, and everything else is True.
Its words:
bool: the type with just two values,TrueandFalse- counts as False: zero (
0,0.0) and empty ("") - counts as True: everything else, even
-3or a single space
Step by step, for bool(value):
- Is it zero? Then
False. - Is it empty, like
""? ThenFalse. - Anything else?
True.
print(bool(0))
print(bool(5))
print(bool(-3))
print(bool(""))
print(bool("hi"))A surprise: bool("0") is True. It's a string with one character in it, so it isn't empty. The same goes for "False".
print(bool("0"))
print(bool("False"))
print(bool(" "))Why does this matter? In Chapter 6, if uses exactly this rule: if name: means "if name isn't empty".
name = ""
print(bool(name))
name = "Rimi"
print(bool(name))It works the other way too: int(True) is 1 and int(False) is 0. That's why True + True is 2.
print(int(True), int(False))
print(True + True)Mistakes and edge cases.
- "False" is True.
bool("False")isTrue: Python doesn't read the word, it only checks that the string isn't empty. - Typed answers are text.
bool(input(...))isFalseonly when the user just presses Enter. If they type0orno, it'sTrue. - A space isn't empty.
bool(" ")isTrue. - Small t again.
bool(true)givesNameError: name 'true' is not defined.
Quiz
What does this print?
print(bool(0))What does this print?
print(bool("0"))What does this print?
print(bool(""))What does this print?
print(True + True + True)Which one is False?
- bool(" ")
- bool(0.0)
- bool(-1)
- bool("no")
The user types no, but this prints True. Which line is the mistake?
answer = input("Do you agree? ") agreed = bool(answer) print(agreed)
Coding tasks
emptyshould hold the bool of an empty string, andfullthe bool of"Python". Usebool()for both.Ask for the user's name. Print
Trueif they typed something, andFalseif they just pressed Enter.