0
0
Pythonprogramming~5 mins

Ternary conditional expression in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a ternary conditional expression in Python?
It is a way to write an if-else statement in one line. It chooses one value if a condition is true, and another if false.
Click to reveal answer
beginner
Write the syntax of a ternary conditional expression.
value_if_true if condition else value_if_false
Click to reveal answer
beginner
How does a ternary conditional expression improve code?
It makes code shorter and easier to read when choosing between two values based on a condition.
Click to reveal answer
beginner
Example: What does this code print? <br>
print('Yes' if 5 > 3 else 'No')
It prints 'Yes' because 5 is greater than 3, so the condition is true.
Click to reveal answer
intermediate
Can ternary conditional expressions be nested?
Yes, you can put one ternary expression inside another to check multiple conditions, but it can become hard to read.
Click to reveal answer
What is the correct way to write a ternary conditional expression in Python?
Avalue_if_true if condition else value_if_false
Bif condition then value_if_true else value_if_false
Ccondition ? value_if_true : value_if_false
Dif condition: value_if_true else value_if_false
What will this print? <br>
print('Even' if 4 % 2 == 0 else 'Odd')
AOdd
BError
CEven
D4 % 2 == 0
Which part of the ternary expression is evaluated first?
AAll at the same time
Bvalue_if_true
Cvalue_if_false
Dcondition
Is this a valid ternary expression? <br>
result = 'Yes' if x > 0 else 'No'
ANo
BYes
COnly if x is defined
DOnly in Python 2
What is a downside of nesting ternary expressions?
AThey can be hard to read
BThey run slower
CThey cause syntax errors
DThey don't work in Python
Explain how a ternary conditional expression works and write a simple example.
Think of it as a short if-else in one line.
You got /4 concepts.
    Describe when it is good to use a ternary conditional expression and when to avoid it.
    Consider how easy your code is to read.
    You got /3 concepts.