Python Control Flow: Conditional Statements 5 — Questions and Answers
Question 1: What is the output? x = [1, 2, 3] if x: print('not empty') else: print('empty')
- not empty (Correct answer)
- empty
- [1, 2, 3]
- True
Correct answer: not empty
A non-empty list is truthy, so the if branch runs and prints 'not empty'.
Question 2: Which of the following will cause a SyntaxError?
- if x > 0: print(x)
- if x > 0:\n print(x)
- if x > 0 print(x) (Correct answer)
- if (x > 0):\n print(x)
Correct answer: if x > 0 print(x)
Python requires a colon `:` at the end of an `if` statement; omitting it causes a SyntaxError.
Question 3: What is the output of this code? color = 'blue' if color == 'red': print(1) elif color == 'green': print(2) elif color == 'blue': print(3) else: print(4)
- 1
- 2
- 3 (Correct answer)
- 4
Correct answer: 3
The third condition `color == 'blue'` is True, so 3 is printed.
Question 4: What is the output? x = 15 if x % 2 == 0: print('even') if x % 3 == 0: print('divisible by 3') if x % 5 == 0: print('divisible by 5')
- even
- divisible by 3
- divisible by 3\ndivisible by 5 (Correct answer)
- divisible by 5
Correct answer: divisible by 3\ndivisible by 5
These are three independent if statements, not an if/elif chain; 15 is divisible by both 3 and 5, so both print.
Question 5: How can you write a one-line if statement in Python?
- if (cond) { stmt; }
- if cond: stmt (Correct answer)
- if cond then stmt
- stmt if cond
Correct answer: if cond: stmt
Python allows `if condition: statement` on a single line when there is only one statement in the block.
Question 6: What is the output of this walrus-operator expression (Python 3.8+)? data = [1, 2, 3] if n := len(data): print(n)
- True
- 3 (Correct answer)
- None
- Error
Correct answer: 3
The walrus operator `:=` assigns `len(data)` to `n` and evaluates it as the condition; 3 is truthy so n (which is 3) is printed.
Question 7: What does `elif` stand for in Python?
- else if (Correct answer)
- else inline function
- external logic if
- evaluated logic if
Correct answer: else if
`elif` is shorthand for 'else if', used to chain multiple conditional checks.
What is the output?
x = [1, 2, 3]
if x:
print('not empty')
else:
print('empty')