6. Ternary
A conditional expression chooses one of two values in a single line. Its form is:
Python evaluates the condition first. If it is True, the whole expression produces value_if_true; otherwise, it produces value_if_false.
Because it is an expression, it produces a value: you can assign it to a variable or pass it to print():
This form is also called a ternary. Unlike an if statement, it has no colon and no indentation, and it always produces exactly one value.
Coming from JavaScript? The order is inverted: Python writes a if condition else b, while JS writes condition ? a : b.
Assign one of two values
Create a variable age with the value 17. Use a conditional expression to assign "Adult" when age >= 18 and "Minor" otherwise to a variable named status, then print status.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Print a conditional expression
Create a variable score with the value 75. Print Pass when score >= 50 and Fail otherwise, using a single conditional expression inside print().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read an age and choose a label
Read an age with input("Age: ") and convert it with int(). Print Adult when the age is 18 or more and Minor otherwise, using a conditional expression.
The simulated user types 20.
Print exactly:
Create a free account to save your progress and unlock chapter 2.