Python Booleans: True, False and Truthy Values - Python with AI tutorial chapter 11
Python

Python Booleans: True, False and Truthy Values

Python with AI Tutorial · Chapter 11 of 48

Python booleans are the two values True and False. They are the answer to every yes-or-no question your program asks: is the invoice paid, is stock below the reorder level, does this list contain anything? Comparisons and conditions produce booleans, and Python also treats every other value as truthy or falsy, which this chapter explains.

The bool type

True and False are keywords, always capitalised, and they belong to the bool type. You can store them in variables just like numbers or strings.

is_paid = True
is_overdue = False

print(is_paid)
print(type(is_paid))
Output:
True
<class 'bool'>

Writing true or TRUE is a NameError because Python is case-sensitive. Names that start with is_, has_ or can_ make boolean variables read naturally in conditions.

Comparisons return booleans

Most booleans are not typed by hand; they come out of a comparison. The six comparison operators compare two values and hand back True or False. You can print that result, store it in a variable for later, or feed it straight into an if statement, and the value is the same in all three cases.

stock = 12
reorder_level = 20

print(stock < reorder_level)
print(stock == 12)
print("Delhi" != "Mumbai")
print(stock >= 20)
Output:
True
True
True
False

Remember that equality uses two equals signs. A single = assigns a value, so if stock = 12: is a syntax error rather than a comparison.

The bool() function and truthy values

Any value can be converted with bool(). Zero, empty containers and None become False; everything else becomes True. Values that convert to True are called truthy and the rest are falsy.

print(bool(0), bool(42), bool(-3))
print(bool(""), bool("Invoice"))
print(bool([]), bool([1, 2]))
print(bool(None))
Output:
False True True
False True
False True
False
Falsy values Truthy values
False True
None Any object that is not None (unless it defines otherwise)
0, 0.0, 0j Any non-zero number, including negatives such as -1
"" (empty string) Any non-empty string, including "0" and "False"
[], (), {}, set() Any list, tuple, dict or set with at least one item
range(0) range(1) or longer

The most surprising row is the string one: "False" is a non-empty string, so it is truthy. When you read a yes/no setting from a file, compare the text explicitly rather than relying on bool().

Truthiness in if statements

An if statement calls bool() on its condition behind the scenes. That means you can test a list, string or number directly instead of writing len(items) > 0 or name != "". Idiomatic Python leans on this heavily.

pending_orders = []
if pending_orders:
    print("Orders waiting")
else:
    print("Nothing to process")

customer_name = "Meera"
if customer_name:
    print(f"Hello, {customer_name}")
Output:
Nothing to process
Hello, Meera
Try it with AI

Ask the assistant to quiz you on truthiness with values that look like they should be one thing but are the other.

Give me a 10-question quiz on Python truthy and falsy values. Each question shows one expression such as bool("0"), bool([[]]), bool(0.0) or bool(" "). Wait for my answer to each one before revealing whether it is True or False and why. Keep score and explain any I get wrong in one sentence.

Combining booleans with and, or, not

The logical operators join or flip boolean results. and is True only when both sides are true, or is True when at least one side is true, and not reverses a value. Python stops evaluating as soon as the answer is known, which is called short-circuiting.

amount = 5400
is_vip = False

print(amount > 5000 and is_vip)
print(amount > 5000 or is_vip)
print(not is_vip)
Output:
False
True
True

Short-circuiting is useful for safety checks such as if orders and orders[0] == "urgent":. If orders is empty, the right-hand side is never run, so there is no IndexError. The operators chapter covers precedence in detail.

Booleans are integers

bool is a subclass of int, with True equal to 1 and False equal to 0. That is why you can add booleans, and why sum() on a list of booleans counts the True values, a handy trick for counting matches.

print(True + True)
print(True == 1, False == 0)

payments = [True, False, True, True]
print(sum(payments), "of", len(payments), "paid")
Output:
2
True True
3 of 4 paid

Functions that return booleans

Many built-in functions and methods return a boolean so they can drop straight into a condition. isinstance() checks a value’s type, any() is True if at least one item in a collection is truthy and all() is True only if every item is truthy.

value = 199.99
print(isinstance(value, float))
print(isinstance(value, (int, float)))
print(isinstance("199.99", float))

invoices_paid = [True, True, False]
print(all(invoices_paid))
print(any(invoices_paid))
Output:
True
True
False
False
True

String methods such as startswith(), isdigit() and in membership tests are also boolean-valued, so if sku.startswith("INV") and sku[4:].isdigit(): reads almost like English.

Booleans in spreadsheets and data files

Booleans rarely arrive in a clean form from the outside world. A CSV export from Excel stores them as the text TRUE and FALSE, a database may use 1 and 0, and a web form might send "yes" and "no". Convert them deliberately once, at the edge of your program, and work with real bool values everywhere else.

raw_values = ["TRUE", "false", "1", "0", "yes", "no"]
truthy_words = {"true", "1", "yes", "y"}

flags = [value.strip().lower() in truthy_words for value in raw_values]
print(flags)
print(sum(flags), "of", len(flags), "are true")
Output:
[True, False, True, False, True, False]
3 of 6 are true

The membership test in truthy_words is itself a boolean expression, so the comprehension produces a proper list of booleans that sum() can count. This pattern turns up again in the pandas chapters when you filter rows with a boolean mask.

Common mistake: writing if is_paid == True:. It works, but is_paid is already a boolean, so if is_paid: says the same thing. Likewise use if not is_paid: rather than if is_paid == False:. Never compare with is True for values that merely might be truthy, such as a non-empty list, because [1] is True is False.
Try it with AI

Give the assistant a small business rule and ask it to turn the rule into a single boolean expression, then to prove it with a truth table.

In Python 3.12, write a function can_ship(stock, backorder_allowed, credit_ok, is_blocked) that returns True only when the customer is not blocked, their credit is ok, and either stock is above zero or backorders are allowed. Return the result as a single boolean expression without if statements. Then print a truth table covering all 16 combinations of the four inputs so I can verify the logic.

Common mistakes

  • Typing true or false in lower case, which Python treats as undefined names.
  • Using = instead of == in a condition.
  • Assuming the string "False" or "0" is falsy. Every non-empty string is truthy.
  • Writing if x == True or if len(items) > 0 when if x and if items are clearer.
  • Expecting and and or to always return a boolean. They return one of their operands, so 0 or "default" gives "default".

Exercise

An order can be dispatched when the customer has cleared credit and either the item is in stock or backorders are allowed. With stock = 0, backorder_allowed = True and credit_ok = False, write one boolean expression for can_dispatch, print it, and then change one variable so it becomes True.

Show answer
stock = 0
backorder_allowed = True
credit_ok = False

can_dispatch = credit_ok and (stock > 0 or backorder_allowed)
print(can_dispatch)

credit_ok = True
can_dispatch = credit_ok and (stock > 0 or backorder_allowed)
print(can_dispatch)
Output:
False
True

The parentheses are not strictly needed because and binds tighter than or, but they make the business rule obvious to the next reader.

Related chapters

FAQ

What are truthy and falsy values in Python?

Falsy values convert to False with bool(): None, zero in any numeric type, and empty strings and containers. Everything else is truthy and is treated as True inside an if or while condition.

Is True equal to 1 in Python?

Yes. bool is a subclass of int, so True == 1 and False == 0 are both True, and you can add booleans or pass them to sum() to count how many conditions were met.

Why is the string “False” truthy?

Because truthiness for strings depends only on length. Any string with at least one character is truthy, including “False”, “0” and a single space, so compare text values explicitly instead of using bool().

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 11 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com