Exercise: Loops
Questions for: Loops
Which of the following is a correct way to iterate over a list in reverse order?
A:
for item in reversed(my_list):
B:
for item in my_list.reverse():
C:
for item in reverse(my_list):
D:
for item in my_list[::-1]:
Answer: A
The
reversed() function is used to iterate over a list in reverse order in Python.
What does the
else block in a for loop execute when the loop is terminated prematurely using a break statement?
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 completes its iterations normally.
Answer: D
The else block in a for loop in Python has a specific behavior: it only executes when the loop completes all its iterations without encountering a break statement.
If a break statement is used to prematurely terminate the loop, the else block is skipped. This is because the break statement interrupts the normal flow of the loop, preventing it from reaching the end.
# Example
for number in range(10):
if number == 5:
break
print(number)
else:
print("The loop completed normally.")
In this example, the loop iterates from 0 to 9. When number reaches 5, the break statement is executed, and the loop terminates early. As a result, the else block is not executed.
Discuss About this Question.
Which function is used to find the minimum value from a sequence?
A:
min()
B:
minimum()
C:
min_value()
D:
find_min()
Answer: A
The
min() function is used to find the minimum value from a sequence in Python.Discuss About this Question.
In Python, what does the
pass statement do when used in a loop?
A:
Exits the loop prematurely.
B:
Does nothing and is used as a placeholder.
C:
Repeats the loop indefinitely.
D:
Terminates the program.
Answer: B
The
pass statement does nothing and is used as a placeholder.Discuss About this Question.
What is the purpose of the
reverse parameter in the range function?
A:
It reverses the order of elements in a list.
B:
It creates a reversed range from a specified end to start.
C:
It reverses the order of iteration in a loop.
D:
It has no effect on the
range function.
Answer: B
The
range function's reverse parameter is used to create a reversed range from a specified end to start.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.