Choosing a value with a conditional expression
Change age, temp, n and x and predict each line. Setting x to 5 shows the other side of the last check.
The conditional expression a if condition else b picks one of two values in a single line. It is perfect for choosing a value, and the or default trick is shorter still but fails when a valid value is falsy, such as 0.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Set n = 4. Print n is even or n is odd using a conditional expression inside a single print.
Set a = 12 and b = 9. Store the bigger of the two in biggest using a conditional expression and print Biggest: 12.
Set nickname = "" and name = "Ravi". Store nickname if it is not empty, otherwise name, in shown, using or, and print it.
Explain it without notes
What is the syntax of the conditional expression, and how is it different from an if statement?
Why can value or default produce a wrong answer, and what is the correct alternative?
Is 10 / x if x != 0 else 0 safe when x is 0? Why?
When should you not use a conditional expression?
Expected output
adult
hot
7 is odd
medium
safe: no division