Exercise: Python

Questions for: Loops

What is the purpose of the enumerate function when used with a for loop?
A:
Counts the total number of iterations.
B:
Iterates over the values of a sequence.
C:
Returns the index and value of each element in a sequence.
D:
Reverses the order of iteration.
Answer: C
The enumerate function is used in a for loop to iterate over both the index and value of each element in a sequence.
How can you create an infinite loop?
A:
for i in range(10):
B:
while True:
C:
for i in range(1, 0, -1):
D:
while False:
Answer: B
while True: creates an infinite loop, as the condition is always true.
In Python, what is the purpose of the else block in a while loop?
A:
It is executed when the loop is terminated prematurely.
B:
It is executed only if an exception occurs in the loop.
C:
It is executed when the loop condition becomes False.
D:
It is executed when the loop condition is True.
Answer: C
The else block in a while loop is executed when the loop condition becomes False.
Which statement is used to iterate over a sequence and execute a block of code as long as a specified condition is True?
A:
for
B:
while
C:
do-while
D:
if
Answer: B
The while loop is used to iterate over a sequence and execute a block of code as long as a specified condition is True.
What does the zip function do when used with loops?
A:
Combines multiple sequences into tuples.
B:
Iterates over the values of a sequence.
C:
Reverses the order of iteration.
D:
Checks for equality of elements in multiple sequences.
Answer: A
The zip function combines multiple sequences into tuples, allowing you to iterate over corresponding elements from each sequence simultaneously.
Ad Slot (Above Pagination)
Quiz