Loops are essential in any programming language, allowing for repetitive tasks to be carried out efficiently. In Python, the primary loop constructs are the <em>for</em>
and <em>while</em>
loops. Check your understanding of Python loops with these 10+ Multiple Choice Questions.
1. Which loop is used to iterate over a sequence (like a list or a string)?
Answer:
Explanation:
The for loop in Python is used to iterate over a sequence.
2. How would you loop through numbers from 1 to 5 in Python?
Answer:
Explanation:
In Python, range(1, 6) generates numbers from 1 to 5. The ending number is exclusive in the range function.
3. Which keyword is used to exit out of a loop prematurely?
Answer:
Explanation:
The break keyword is used to exit a loop before it has finished iterating.
4. Which keyword will skip the current iteration and continue with the next one?
Answer:
Explanation:
The continue keyword is used to skip the current iteration of a loop and proceed to the next one.
5. What is the output of the following code?
for i in range(3):
print(i)
Answer:
Explanation:
By default, range(n) starts from 0 and goes up to, but does not include, n.
6. How would you loop over a string one character at a time?
Answer:
Explanation:
Strings are sequences in Python, and each character of a string can be accessed using a for loop directly.
7. Which of the following results in an infinite loop?
Answer:
Explanation:
while True: will always evaluate as true, causing the loop to run indefinitely.
8. What does the else clause do in a Python loop?
Answer:
Explanation:
The else clause in a Python loop is executed when the loop finishes normally (i.e., without encountering a break).
9. Which loop is typically used when you know beforehand how many times you want to iterate?
Answer:
Explanation:
The for loop is typically used when you know the number of iterations beforehand, often determined by the length of a sequence or the parameters of the range() function.
10. Which function would you use to get numbers in descending order, starting from 5 and ending at 1?
Answer:
Explanation:
range(5, 0, -1) starts at 5 and decrements the number by 1 until reaching 0 (exclusive).
11. Which statement is used to represent a block of code/body of a loop that does nothing?
Answer:
Explanation:
The pass statement is a null operation; nothing happens when it executes. It is useful as a placeholder where a statement is syntactically needed but no action is required.
12. In a nested loop, what does the break statement do if it is encountered?
Answer:
Explanation:
When a break statement is encountered inside a nested loop, only the innermost loop in which the break exists is exited.
Looping is fundamental in programming. I hope these questions enhanced your understanding of loops in Python. Keep practicing and happy coding!