Python Control Flow: Conditional Statements 3 — Questions and Answers
Question 1: What is the output of: x = None if x: print('truthy') else: print('falsy')
- truthy
- falsy (Correct answer)
- None
- Error
Correct answer: falsy
None is falsy in Python, so the else branch executes and prints 'falsy'.
Question 2: Which of the following correctly checks if a variable `n` is between 1 and 10 inclusive?
- if 1 <= n <= 10: (Correct answer)
- if n >= 1 and =< 10:
- if (1 <= n) & (n <= 10):
- if n in range(1, 10):
Correct answer: if 1 <= n <= 10:
Python supports chained comparisons like `1 <= n <= 10`, which is the most Pythonic way.
Question 3: What does `pass` do inside an `if` block?
- Skips to the next iteration
- Exits the program
- Does nothing; acts as a placeholder (Correct answer)
- Returns None
Correct answer: Does nothing; acts as a placeholder
`pass` is a no-op statement used as a syntactic placeholder when a block is required but no action is needed.
Question 4: What is the output? for i in range(3): if i == 1: pass else: print(i)
- 0 1 2
- 0 2 (Correct answer)
- 1
- 0 1
Correct answer: 0 2
When i==1 the `pass` does nothing and no print occurs, so only 0 and 2 are printed.
Question 5: Which of the following correctly uses `not` in an if statement?
- if not x == 5: (Correct answer)
- if x not 5:
- if !(x == 5):
- if x <> 5:
Correct answer: if not x == 5:
`not` is Python's logical negation operator and `not x == 5` is valid syntax.
Question 6: What is printed? val = '' if val: print('has value') elif val is None: print('is None') else: print('empty')
- has value
- is None
- empty (Correct answer)
- Error
Correct answer: empty
An empty string is falsy but not None, so neither the if nor the elif match, and 'empty' is printed.
Question 7: In Python, `if x is None:` differs from `if x == None:` because:
- They are identical
- `is` checks identity, while `==` checks equality (Correct answer)
- `==` checks identity, while `is` checks equality
- `is` only works with strings
Correct answer: `is` checks identity, while `==` checks equality
`is` tests object identity (same object in memory), while `==` tests value equality; PEP 8 recommends `is None`.
What is the output of:
x = None
if x:
print('truthy')
else:
print('falsy')