CodeBlanks Logo Icon CodeBlanks

Conditional expression

Learn single-line conditionals with x if cond else y.

Conditional expression

A conditional expression (or ternary) writes if/else in one line:

age = 20
status = "Adult" if age >= 18 else "Child"
print(status)

The form is: value_if_true if condition else value_if_false. This is handy for simple assignments; complex logic prefers normal if/else.

Using conditional expressions

The conditional expression is especially useful for variable assignment:

score = 75
result = "Passed" if score >= 50 else "Failed"
print(result)

The same logic can be written with if/else but this is shorter. Never nest conditional expressions; it gets unreadable.

Practice Print a conditional expression

Assign score = 75. Assign result = "Passed" if score >= 50 else "Failed". Print print(result).

Starter code

main.py
# Conditional expression

Sample solution

main.py
score = 75
result = "Passed" if score >= 50 else "Failed"
print(result)

Expected output

Passed

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If age is 20, what does "Adult" if age >= 18 else "Child" give?

  • Error
  • Child
  • Adult Correct answer
  • None

Explanation: 20 >= 18 is True, the first value is taken.

2 Complete the conditional expression

Question
status = "Adult" ____ age >= 18 else "Child"
Answer
status = "Adult" if age >= 18 else "Child"

Explanation: if separates the condition in a conditional expression.

3 Match the conditional expression parts

Term Meaning
value if When true
condition After if
else When false
one line Conditional expression advantage

All lessons in Beginner