Course outline · 0% complete

0/32 lessons0%

Course overview →

Truthiness and Nesting

lesson 4-3 · ~11 min · 12/32

Truthiness: any value can be a condition

Real data goes missing constantly: a form field left blank, a search that matched nothing, a counter still at zero. Checks for that kind of emptiness are so common that Python lets any value stand directly as a condition, and if name: is a line you will read in almost every Python codebase.

An if does not require a literal True or False. Python treats every value as truthy or falsy. The falsy list is short:

  • 0 and 0.0
  • the empty string ""
  • None (Python's value meaning nothing here)
  • False
  • empty containers (you will meet lists in unit 6, [] is falsy too)

Everything else counts as True. So if name: reads as if name is not empty, which is exactly the Pythonic way to write it:

name = ""
if name:
    print("hello", name)
else:
    print("no name given")

Watch the trap: the string "False" is truthy, because the rule is about emptiness, not the text inside.

Code exercise · python

Run this. Both conditions are values, not comparisons. Predict each branch first: `name` is empty, `count` is zero.

Nesting: an if inside an if

Branches can contain whole new if statements. Each level indents 4 more spaces:

if user == "ada":
    if pw == "secret":
        print("welcome")
    else:
        print("wrong password")
else:
    print("unknown user")

Nesting expresses dependent questions: the password only matters once the user matched. If your questions are independent alternatives, a flat elif chain (lesson 4-1) reads better. Two levels of nesting is normal, four is a sign to reorganize.

Quiz

Which value is truthy?

Code exercise · python

Your turn. Implement the login check from the text: if `user` equals `ada`, then check `pw`. Matching password prints `welcome`, wrong password prints `wrong password`, any other user prints `unknown user`. With the given values it should print `welcome`.

Code exercise · python

One more, the pattern in the wild. `name` arrived from a form as spaces only. Strip it, then use `if not name:` to substitute `guest` when nothing remains, and print the greeting `welcome, guest` with an f-string.