Truthy values and nested ifs

Making Decisions, lesson 5 of 5

🔀 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):

  • 0 and 0.0
  • the empty string ""
  • None and empty collections like []

Everything else is truthy. So if name: means "if name is not empty". bool(value) shows how a value is treated.

Example

Truthy or falsy?

Set name = "Ada". Note that a single space " " is truthy!

Quiz

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.

Example

Nesting and one-liners

One line per input() call

Try the usernames al and grace, and change items to 1.

Exercise

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

Quiz

What does this print?

Exercise

Plural helper

Use a one-line conditional expression to set word to "apple" when count is 1 and "apples" otherwise.