Python 3D Academyবাংলা

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, True and False
  • counts as False: zero (0, 0.0) and empty ("")
  • counts as True: everything else, even -3 or a single space

Step by step, for bool(value):

  1. Is it zero? Then False.
  2. Is it empty, like ""? Then False.
  3. 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(" "))
Even a single space counts as something.

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") is True: Python doesn't read the word, it only checks that the string isn't empty.
  • Typed answers are text. bool(input(...)) is False only when the user just presses Enter. If they type 0 or no, it's True.
  • A space isn't empty. bool(" ") is True.
  • Small t again. bool(true) gives NameError: name 'true' is not defined.

Quiz

  1. What does this print?

    print(bool(0))
  2. What does this print?

    print(bool("0"))
  3. What does this print?

    print(bool(""))
  4. What does this print?

    print(True + True + True)
  5. Which one is False?

    • bool(" ")
    • bool(0.0)
    • bool(-1)
    • bool("no")
  6. 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

  1. empty should hold the bool of an empty string, and full the bool of "Python". Use bool() for both.

  2. Ask for the user's name. Print True if they typed something, and False if they just pressed Enter.