Exercise: Loops
Questions for: Loops
What is the purpose of the
zip function in Python when used with loops?
A:
Counts the total number of iterations
B:
Combines multiple sequences into tuples
C:
Returns the index and value of each element in a sequence
D:
Reverses the order of iteration
Answer: B
The
zip function is used to combine multiple sequences into tuples, allowing you to iterate over corresponding elements from each sequence simultaneously.
Which of the following statements accurately describes the behavior of the
else block in a Python while loop?
A:
It is executed when the loop condition is True.
B:
It is executed when the loop is terminated prematurely.
C:
It is executed only if an exception occurs in the loop.
D:
It is executed when the loop condition becomes False.
Answer: D
The
else block in a while loop is executed when the loop condition becomes False.Discuss About this Question.
What does the
enumerate function do when used in a for loop?
A:
Counts the total number of iterations
B:
Iterates over the values of a sequence
C:
Adds an index to each element in an iterable
D:
Reverses the order of iteration
Answer: C
The enumerate() function adds an index to each element in an iterable, returning pairs of index and element.
my_list = ['apple', 'banana', 'orange', 'grape']
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
Output:
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
Index: 3, Value: grapeDiscuss About this Question.
Which loop in Python is used for iterating over a sequence until a specified condition is False?
A:
for loop
B:
while loop
C:
do-while loop
D:
if loop
Answer: B
The
while loop continues to execute a block of code as long as the specified condition is True.Discuss About this Question.
What is the purpose of the else block in a Python
for or while loop?
A:
It handles exceptions that occur in the loop.
B:
It is executed only if an exception occurs in the loop.
C:
It ensures the code inside the
else block always executes, regardless of whether an exception occurs or not.
D:
It is executed when the loop condition becomes False.
Answer: D
The
else block in a loop is executed when the loop condition becomes False, and the loop naturally exits.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.