🔀 Making Decisions, lesson 5 of 5
Truthy values and nested ifs
Use any value as a condition, nest decisions and write one-line if expressions.
10 min
2 exercises
2 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
Any value can be used as a condition. Python treats
these as falsy (like False):
0and0.0- the empty string
"" Noneand empty collections like[]
Everything else is truthy. So if name: means
"if name is not empty". bool(value) shows how a
value is treated.
Truthy or falsy?
Set name = "Ada". Note that a single space " " is truthy!
What does this print?
You can put an if inside another if
(nesting). Each level is indented a bit further. Keep
nesting shallow: often elif or and reads better.
For simple either/or values there's a one-line
conditional expression:
result = a if condition else b.
Nesting and one-liners
One line per input() call
Try the usernames al and grace, and change items to 1.
Username checker
Check the typed username and print exactly one message:
- empty →
Please type a username - shorter than 3 characters →
Too short - otherwise →
Welcome, <name>!
The test types Al, so your program should print
Too short.
Your program receives this input: Al
What does this print?
Plural helper
Use a one-line conditional expression to set word
to "apple" when count is 1 and "apples"
otherwise.