Python Control Flow: Conditional Statements 2 — Questions and Answers
Question 1: What does the following code print? x = 10 if x > 5: print('A') elif x > 8: print('B') else: print('C')
- A (Correct answer)
- B
- C
- A and B
Correct answer: A
The first condition `x > 5` is True, so 'A' is printed and the rest of the elif/else chain is skipped.
Question 2: Which operator is used for the ternary (conditional) expression in Python?
- ?:
- if/else inline (Correct answer)
- switch
- cond
Correct answer: if/else inline
Python uses `value_if_true if condition else value_if_false` as its ternary expression syntax.
Question 3: What is the output of: `print('yes' if 0 else 'no')`?
- yes
- no (Correct answer)
- None
- Error
Correct answer: no
0 is falsy in Python, so the else branch evaluates and 'no' is printed.
Question 4: Which of the following is a valid Python conditional expression?
- x = (a > b) ? a : b
- x = a if a > b else b (Correct answer)
- x = if a > b then a else b
- x = a when a > b otherwise b
Correct answer: x = a if a > b else b
Python's conditional (ternary) expression syntax is `value_if_true if condition else value_if_false`.
Question 5: What happens if no `elif` or `else` clause is present and the `if` condition is False?
- A SyntaxError is raised
- The program crashes
- Nothing happens; execution continues after the block (Correct answer)
- Python asks for input
Correct answer: Nothing happens; execution continues after the block
If the `if` condition is False and there are no other branches, Python simply skips the block and continues.
Question 6: What is the result of the following? age = 20 status = 'adult' if age >= 18 else 'minor' print(status)
- minor
- adult (Correct answer)
- 20
- None
Correct answer: adult
Since `age >= 18` is True, the ternary expression evaluates to 'adult'.
Question 7: In Python, how many `elif` clauses can follow a single `if` statement?
- Only 1
- At most 3
- At most 10
- Unlimited (Correct answer)
Correct answer: Unlimited
Python allows any number of `elif` clauses after an `if` statement.
What does the following code print?
x = 10
if x > 5:
print('A')
elif x > 8:
print('B')
else:
print('C')