Python Programming - Loops

Exercise : Loops - General Questions
  • Loops - General Questions
26.
Which loop is used for iterating over the characters of a string?
for loop
while loop
do-while loop
if loop
Answer: Option
Explanation:
The for loop is commonly used for iterating over the characters of a string in Python.
my_string = "Hello"

for char in my_string:
    print(char)
In this example, the for loop iterates over each character in the string my_string and prints it to the console.

27.
What does the range function return when used with two arguments, start and stop?
A sequence from start to stop (exclusive)
A sequence from start to stop (inclusive)
A sequence of even numbers from start to stop
A reversed sequence from start to stop (inclusive)
Answer: Option
Explanation:
The range function with two arguments returns a sequence of numbers from start to stop (exclusive).

28.
What is the purpose of the reverse parameter in the sorted function?
It reverses the order of elements in a list.
It creates a reversed range from a specified end to start.
It reverses the order of iteration in a loop.
It sorts the elements in descending order.
Answer: Option
Explanation:
The reverse parameter in the sorted function is used to sort the elements in descending order.

29.
In Python, what does the enumerate function return when used with a for loop?
Index and value of each element in a sequence
Values of a sequence
Reversed order of elements in a sequence
Total number of iterations
Answer: Option
Explanation:
The enumerate function returns the index and value of each element in a sequence when used with a for loop.

30.
Which of the following is the correct syntax for a do-while loop?
do { } while condition;
while condition: { }
do: 
 code 
while condition
while True: 
    code 
    if not condition: break
Answer: Option
Explanation:
Python does not have a built-in do-while loop, but it can be simulated using a while loop with a break statement to exit the loop based on a condition.