Python Control Flow: Conditional Statements 4 — Questions and Answers
Question 1: What is the output of the following nested conditional? x, y = 3, 7 if x < 5: if y > 5: print('A') else: print('B') else: print('C')
- A (Correct answer)
- B
- C
- Error
Correct answer: A
Both `x < 5` and `y > 5` are True, so the innermost branch prints 'A'.
Question 2: What will this print? num = 0 if num: print(num) else: print('zero')
- 0
- zero (Correct answer)
- False
- None
Correct answer: zero
0 is falsy, so the else branch runs and prints 'zero'.
Question 3: Which statement about Python's `match` statement (Python 3.10+) is TRUE?
- It replaces if/elif but uses the same syntax
- It provides structural pattern matching similar to switch in other languages (Correct answer)
- It only works with integers
- It is available in Python 2.7+
Correct answer: It provides structural pattern matching similar to switch in other languages
Python 3.10 introduced `match`/`case` for structural pattern matching, which can replace complex if/elif chains.
Question 4: What is the output? x = 5 result = 'big' if x > 10 else 'medium' if x > 3 else 'small' print(result)
- big
- medium (Correct answer)
- small
- Error
Correct answer: medium
x > 10 is False, so the first else is evaluated; x > 3 is True, so 'medium' is returned.
Question 5: What is the correct way to check if a key exists in a dictionary before using it in an if statement?
- if key in dict: (Correct answer)
- if dict.has(key):
- if dict.contains(key):
- if dict[key] exists:
Correct answer: if key in dict:
The `in` operator checks for key membership in a dictionary in Python.
Question 6: What does the following code print? a, b = True, False if a and not b: print('X') else: print('Y')
- X (Correct answer)
- Y
- True
- Error
Correct answer: X
`a` is True and `not b` is True, so `a and not b` is True and 'X' is printed.
Question 7: In Python, which of the following values is considered TRUTHY?
- 0
- []
- ""
- "0" (Correct answer)
Correct answer: "0"
A non-empty string like "0" is truthy; 0, empty list [], and empty string "" are all falsy.
What is the output of the following nested conditional?
x, y = 3, 7
if x 5:
print('A')
else:
print('B')
else:
print('C')