Hackerrank Control Flow and Looping 2 — Questions and Answers
Question 1: What is the output of the following code? ```python for i in range(10): if i % 2 == 0: continue if i > 6: break print(i) ```
- 1 3 5 (Correct answer)
- 1 3 5 7
- 0 2 4 6
- 1 3 5 7 9
Correct answer: 1 3 5
The loop prints odd numbers (continue skips evens) and stops before printing 7 (break when i > 6).
Question 2: Which loop construct is most appropriate when you need to iterate over a list and also need the index of each element?
- for i in range(len(lst))
- for item in lst
- for i, item in enumerate(lst) (Correct answer)
- while i < len(lst)
Correct answer: for i, item in enumerate(lst)
enumerate() returns both index and value, making it the Pythonic way to access both simultaneously.
Question 3: What does the `else` clause of a `for` loop execute?
- Only when the loop body raises an exception
- Only when the loop completes without a break statement (Correct answer)
- Only when the loop runs zero iterations
- Every time the loop condition is False
Correct answer: Only when the loop completes without a break statement
The else block of a for loop runs when the loop finishes normally (without being terminated by break).
Question 4: What is the output of this code? ```python x = 5 result = 'positive' if x > 0 else 'negative' if x < 0 else 'zero' print(result) ```
- positive (Correct answer)
- negative
- zero
- Error
Correct answer: positive
The chained ternary evaluates left-to-right: x > 0 is True so result is 'positive'.
Question 5: Which statement about `while True:` loops is correct?
- They are syntax errors in Python
- They always run exactly once
- They run indefinitely unless broken by a break or return (Correct answer)
- They automatically stop after 100 iterations
Correct answer: They run indefinitely unless broken by a break or return
while True creates an infinite loop that only exits via break, return, or an exception.
Question 6: What is the output of: ```python count = 0 for i in range(5): for j in range(5): if i == j: count += 1 print(count) ```
- 5 (Correct answer)
- 10
- 25
- 0
Correct answer: 5
i == j is true exactly once per value of i (when j equals i), giving 5 matches total.
Question 7: What happens when you use `pass` inside an `if` block?
- It exits the current function
- It skips the current iteration of the loop
- It does nothing and execution continues normally (Correct answer)
- It raises a SyntaxError
Correct answer: It does nothing and execution continues normally
pass is a null operation — it does nothing and allows the block to be syntactically complete.
What is the output of the following code?
```python
for i in range(10):
if i % 2 == 0:
continue
if i > 6:
break
print(i)
```