1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

One-line if

When you only need to pick between two values, a conditional expression fits on one line:

status = "adult" if age >= 18 else "minor"

Read it as: "adult" if this is true, otherwise "minor".

See it run

n = 12
size = "big" if n > 10 else "small"
print(size)
n = 3
size = "big" if n > 10 else "small"
print(size)

One line, two possible values. Python checks the condition in the middle first.

Practice one-line if

Exercise 1

With n = 7, set parity to "even" or "odd" in one line using % and a conditional expression.

Exercise 2

A member pays 6; everyone else pays 9. With member = False, assign price using one conditional expression.

Exercise 3

A reading goal is met at 20 pages or more. With pages = 18 and goal = 20, set message to "Goal met" or an f-string such as "2 pages left" using a conditional expression and subtraction.

Free lesson: use the editor to practice it.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest