Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 149 ยท Data Types

Booleans and Truthiness

Learn how Python's bool type works, which values count as truthy or falsy, how bool() converts values, and why True behaves like the number 1.

A Boolean is the simplest value a program can hold: it's either True or False. Every decision your code makes, from "is the password long enough?" to "should this loop keep going?", comes down to one of these two values.

Python's Boolean type is called bool. In this lesson you'll create Booleans, see where they come from, and learn about truthiness: the rule that lets any Python value stand in for True or False. Truthiness is one of the features that makes Python code short and readable, so it's worth understanding well.

True and False

Python has exactly two Boolean values, written True and False. They're keywords, so the capital letter matters: true (lowercase) is just an unknown name and raises a NameError.

Python The two Booleans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You rarely type True or False directly. Most Booleans are produced by an expression that asks a question: age >= 18, name == "Ada", "@" in email. You'll meet all of these operators in Comparison and Logical Operators. For now, the key idea is that a comparison evaluates to a bool, which you can store in a variable like any other value.

Tip: Name Boolean variables so they read like a yes-or-no question: is_valid, has_items, can_edit, should_retry. Then if is_valid: reads almost like English.

Booleans are numbers in disguise

Here's something that surprises many learners: bool is a subclass of int. True behaves like 1 and False behaves like 0. This is mostly a historical detail, but it has one genuinely useful consequence: you can add up Booleans to count how many are True.

Python Counting with True

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last example uses a generator expression (you'll learn those in Dictionary and Set Comprehensions): it produces one Boolean per score, and sum() counts the True ones. It's a compact, common Python idiom.

Warning: Don't do arithmetic with Booleans just because you can. total = price * is_member works, but total = price if is_member else 0 says what you mean. Counting with sum() is the main place where the number trick earns its keep.

Truthiness: every value has a Boolean meaning

Wherever Python needs a yes-or-no answer, such as after if or while, it accepts any value, not just True and False. Python decides whether the value counts as true or false using a simple rule:

  • Falsy values are "empty" or "zero": False, None, 0, 0.0, 0j, "" (empty string), [], (), {}, set(), and range(0).
  • Truthy values are everything else: any non-zero number, any non-empty string or collection, and most objects.

A value that acts like True is called truthy; one that acts like False is called falsy. The built-in bool() function shows you which is which.

Python Truthy or falsy?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look closely at a few results:

  • -3 is truthy. Only zero is falsy; negative numbers are not.
  • " " (a single space) is truthy because the string isn't empty.
  • "False" is truthy. It's a five-letter string, not the Boolean False.
  • [0] is truthy: the list contains one item, even though that item is falsy.

The !r inside the f-string shows each value's representation, so you can see the quotes around strings. You learned about that in String Formatting.

Using truthiness in conditions

Truthiness lets you write checks that are short and clear. Instead of comparing a list's length to zero, you can test the list itself:

Python Checking for empty values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The nickname is an empty string, which is falsy, so the expression nickname or "Guest" picks the fallback. Put a name between the quotes and run it again to see the other result. (You'll learn exactly how or picks its result in Comparison and Logical Operators.)

PEP 8, Python's style guide, recommends this style: write if items: rather than if len(items) > 0:, and if not name: rather than if name == "":.

When truthiness is the wrong tool

Truthiness lumps all falsy values together, and sometimes that hides a real difference. Suppose a function returns a temperature, or None when the sensor is offline:

Python
reading = 0  # a real measurement: zero degrees

if not reading:
    print("Sensor offline")  # wrong! 0 is a valid reading

Zero is falsy, so the check fires even though the sensor works. When 0 or "" is a legitimate value, test for the specific thing you mean, here if reading is None:. The next lesson, None, covers that check in detail.

The bool() function

bool(value) converts any value to True or False using the truthiness rules above. You rarely need it inside an if, because the if already does the conversion. It's useful when you want to store or print the Boolean result:

Python Converting with bool()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Warning: bool("False") is True, and so is bool("0"). Any non-empty string is truthy. When you read yes/no answers from a user or a file, compare the text against the words you accept, as in the newsletter example above.

Booleans in your own objects

Your own classes are truthy by default. A class can change that by defining __bool__ (or __len__, so that an empty container is falsy). You'll learn how in Special (Dunder) Methods. It's the same mechanism that makes empty lists and strings falsy.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these values is truthy?

    "0" is a non-empty string, so it's truthy. The number 0, the empty string and the empty list are all falsy.
  2. 2. What does sum([True, True, False, True]) return?

    bool is a subclass of int, so True counts as 1 and False as 0. The sum is 3.
  3. 3. Which line causes an error?

    Booleans are written True and False with a capital letter. Lowercase false is an undefined name, so Python raises a NameError.
  4. 4. A function returns a count, which can be 0, or None when the data is missing. Which check correctly detects missing data?

    not count is also true when count is 0, which is a valid value. Checking is None targets exactly the missing case.

Summary

  • bool has two values, True and False, written with a capital letter.
  • Comparisons such as age >= 18 produce Booleans you can store and print.
  • bool is a subclass of int: True == 1 and False == 0, so sum() can count True values.
  • Falsy values are False, None, zero and empty collections; everything else is truthy.
  • Write if items: and if not text: to test for emptiness, but test is None when 0 or "" are valid values.
  • bool(value) converts any value; bool("False") is still True.

Next: None, Python's way of saying "no value here".