Python Programming - Loops

Exercise : Loops - General Questions
  • Loops - General Questions
1.
What will be the output of the following code?
for i in range(3):
    print(i)
0
1
2
0 1 2
Answer: Option
Explanation:
The range(3) generates values 0, 1, and 2, and the for loop iterates over these values, printing them.

2.
Which keyword is used to skip the rest of the code in the current iteration of a loop and move to the next iteration?
pass
continue
skip
next
Answer: Option
Explanation:
The continue statement is used to skip the rest of the code in the current iteration of a loop and move to the next iteration.

3.
What is the purpose of the else block in a Python for or while loop?
It handles exceptions that occur in the loop.
It is executed only if an exception occurs in the loop.
It ensures the code inside the else block always executes, regardless of whether an exception occurs or not.
It is executed when the loop condition becomes False.
Answer: Option
Explanation:
The else block in a loop is executed when the loop condition becomes False, and the loop naturally exits.

4.
Which loop in Python is used for iterating over a sequence until a specified condition is False?
for loop
while loop
do-while loop
if loop
Answer: Option
Explanation:
The while loop continues to execute a block of code as long as the specified condition is True.

5.
What does the enumerate function do when used in a for loop?
Counts the total number of iterations
Iterates over the values of a sequence
Adds an index to each element in an iterable
Reverses the order of iteration
Answer: Option
Explanation:

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: grape