Control Flow and Looping Flashcards
7 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 7 Control Flow and Looping flashcards as text
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) ```
Answer: 1 3 5
The loop prints odd numbers (continue skips evens) and stops before printing 7 (break when i > 6).
Which loop construct is most appropriate when you need to iterate over a list and also need the index of each element?
Answer: for i, item in enumerate(lst)
enumerate() returns both index and value, making it the Pythonic way to access both simultaneously.
What does the `else` clause of a `for` loop execute?
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).
What is the output of this code? ```python x = 5 result = 'positive' if x > 0 else 'negative' if x < 0 else 'zero' print(result) ```
Answer: positive
The chained ternary evaluates left-to-right: x > 0 is True so result is 'positive'.
Which statement about `while True:` loops is 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.
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) ```
Answer: 5
i == j is true exactly once per value of i (when j equals i), giving 5 matches total.
What happens when you use `pass` inside an `if` block?
Answer: It does nothing and execution continues normally
pass is a null operation — it does nothing and allows the block to be syntactically complete.