0
0
Pythonprogramming~20 mins

Ternary conditional expression in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ternary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested ternary conditional expression
What is the output of this Python code?
Python
x = 5
y = 10
result = 'A' if x > y else 'B' if x == y else 'C'
print(result)
AB
BA
CC
DSyntaxError
Attempts:
2 left
💡 Hint
Remember how chained ternary expressions evaluate from left to right.
Predict Output
intermediate
2:00remaining
Ternary expression with function calls
What will be printed by this code?
Python
def f():
    return 1

def g():
    return 2

value = f() if False else g()
print(value)
A2
B1
CNone
DTypeError
Attempts:
2 left
💡 Hint
The condition is False, so the else part runs.
Predict Output
advanced
2:00remaining
Ternary expression with side effects
What is the output of this code snippet?
Python
x = 0
result = (x := x + 1) if True else (x := x + 2)
print(x, result)
ASyntaxError
B2 2
C1 2
D1 1
Attempts:
2 left
💡 Hint
The walrus operator assigns and returns the value.
Predict Output
advanced
2:00remaining
Ternary expression with different data types
What will this code print?
Python
value = 10
result = 'Even' if value % 2 == 0 else 0
print(type(result))
ASyntaxError
B<class 'str'>
CTypeError
D<class 'int'>
Attempts:
2 left
💡 Hint
The ternary expression returns either a string or an integer.
🧠 Conceptual
expert
2:00remaining
Understanding ternary expression evaluation order
Consider the expression:
result = 'X' if False else 'Y' if True else 'Z'

What is the value of result after this runs?
A'Y'
B'X'
C'Z'
DSyntaxError
Attempts:
2 left
💡 Hint
Ternary expressions are evaluated left to right, and else can contain another ternary.