Python Arena
Step 1 of 4

Conditional expressions

An if statement chooses which code runs. Often, though, the only thing that changes is a value:

temperature = 25
if temperature > 20:
    print("warm")
else:
    print("cold")
Output
warm

A conditional expression chooses between two values in one line. It reads almost like English: "warm" if temperature > 20 else "cold" is "warm" when the condition is true, and "cold" otherwise. Since it's an expression, it goes anywhere a value can go:

temperature = 25
print("warm" if temperature > 20 else "cold")
label = "even" if temperature % 2 == 0 else "odd"
print(label)
Output
warm
odd

The order is: the value for true, then if and the condition, then else and the value for false. (Some languages call this the ternary operator, because it has three parts.)

Where it shines

Small choices inside a longer line, such as a word that changes with a number, are where a conditional expression saves the most. Without it, each line would need an if statement of four lines:

for count in [0, 1, 5]:
    print(f"{count} {'file' if count == 1 else 'files'} found")
Output
0 files found
1 file found
5 files found

It works in a return too:

def larger(a, b):
    return a if a > b else b


print(larger(3, 8))
print(larger(10, -2))
Output
8
10

The else is not optional

An expression must always have a value, so the else part is required. Without it, Python can't read the line:

score = 7
print("passed" if score >= 5)
Python stops with
  File "main.py", line 2
    print("passed" if score >= 5)
          ^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: expected 'else' after 'if' expression

Use a conditional expression to choose a value. When the two cases do different things, or there are more than two cases, an ordinary if, elif and else is easier to read.

Your task

Challenge 1 of 3

Fill in the blanks so the program sets status to "adult" for an age of 18 or more and to "minor" otherwise. For example:

Age: 20
Status: adult

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Write a function plural(count, word) that returns the count and the word, with an s added to the word unless the count is exactly 1: plural(1, "apple") returns "1 apple", and plural(3, "apple") returns "3 apples". Choose between the two with a conditional expression, not an if statement.