Python Programming - Loops

Exercise : Loops - General Questions
  • Loops - General Questions
21.
What does the else block in a for loop execute when the loop is terminated prematurely using a break statement?
It is executed when the loop condition is True.
It is executed when the loop is terminated prematurely.
It is executed only if an exception occurs in the loop.
It is executed when the loop completes its iterations normally.
Answer: Option
Explanation:

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.


22.
Which of the following is a correct way to iterate over a list in reverse order?
for item in reversed(my_list):
for item in my_list.reverse():
for item in reverse(my_list):
for item in my_list[::-1]:
Answer: Option
Explanation:
The reversed() function is used to iterate over a list in reverse order in Python.

23.
Which of the following is the correct syntax to define an infinite loop?
for i in range(10):
while True:
while False:
for i in range(1, 0, -1):
Answer: Option
Explanation:
while True: creates an infinite loop, as the condition is always true.

24.
In Python, what is the purpose of the break statement in a loop?
Skips the remaining code in the loop and moves to the next iteration.
Exits the loop prematurely.
Repeats the loop indefinitely.
Jumps to the next loop iteration.
Answer: Option
Explanation:
The break statement is used to exit a loop prematurely, regardless of the loop's condition. Here's an example of using the break statement in a loop:
for i in range(1, 6):
    if i == 3:
        break
    print(i)
In this example, when the value of i becomes 3, the break statement is executed, causing the loop to terminate prematurely. As a result, only the numbers 1 and 2 are printed before the loop is exited.

25.
Which loop in Python is primarily used for iterating over a sequence of numbers with a specified step size?
for loop
while loop
do-while loop
if loop
Answer: Option
Explanation:
The for loop in Python is commonly used for iterating over a sequence of numbers with a specified step size.
for i in range(0, 10, 2):  # start at 0, stop before 10, step size of 2
    print(i)
In this example, the for loop iterates over the sequence of numbers from 0 to 8 (10 is not included) with a step size of 2, and prints each number to the console.