The for
loop in Python is a control flow statement that is used to iterate over a sequence (such as a list, tuple, set, dictionary, or string) or other iterable objects. Here we present 12 multiple-choice questions to test your knowledge of Python For Loop. Each MCQ has the correct answer with an explanation.
1. What is the basic structure of a for loop in Python?
Answer:
Explanation:
In Python, a for loop iterates over items of an iterable using the syntax 'for item in iterable:'.
2. How do you iterate over a range of numbers from 0 to 4 in Python?
Answer:
Explanation:
Both range(5) and range(0, 5) produce a sequence of numbers from 0 to 4.
3. How can you loop through a dictionary and access both keys and values?
Answer:
Explanation:
The items() method returns key-value pairs, which can be unpacked in a for loop.
4. What does the 'break' statement do inside a for loop?
Answer:
Explanation:
The 'break' statement is used to exit the for loop before it has iterated over all items.
5. What is the role of the 'continue' statement in a for loop?
Answer:
Explanation:
The 'continue' statement skips the rest of the code inside a loop for the current iteration.
6. How do you iterate over both the elements of a list and their indices?
Answer:
Explanation:
You can use enumerate(my_list) or loop over the indices using range(len(my_list)).
7. What is the correct syntax for iterating over a list using a for loop?
Answer:
Explanation:
The syntax for iterating over a list is 'for item in list:'.
8. How do you loop through the characters of a string 'hello'?
Answer:
Explanation:
You can loop through a string directly by iterating over its characters.
9. What is the output of the following code?
for i in range(3):
print(i)
else:
print("Done")
Answer:
Explanation:
The for loop iterates over 0, 1, 2, and then the else block is executed, printing "Done".
10. How can you loop through a tuple (1, 2, 3) and print each number?
Answer:
Explanation:
You can iterate through a tuple by directly looping over its elements.
11. How do you create a nested for loop to iterate over a 2×2 matrix [[1,2],[3,4]]?
Answer:
Explanation:
Both methods correctly iterate over a nested list or matrix.
12. What is the purpose of the 'else' clause in a for loop?
Answer:
Explanation:
In Python, the else block in a for loop is executed when the loop completes normally without a break.