Exercise: Loops
Questions for: Loops
What does the
range function return when used with two arguments, start and stop?
A:
A sequence from
start to stop (exclusive)
B:
A sequence from
start to stop (inclusive)
C:
A sequence of even numbers from
start to stop
D:
A reversed sequence from
start to stop (inclusive)
Answer: A
The
range function with two arguments returns a sequence of numbers from start to stop (exclusive).
Which loop is used for iterating over the characters of a string?
A:
for loop
B:
while loop
C:
do-while loop
D:
if loop
Answer: A
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.Discuss About this Question.
Which loop in Python is primarily used for iterating over a sequence of numbers with a specified step size?
A:
for loop
B:
while loop
C:
do-while loop
D:
if loop
Answer: A
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.Discuss About this Question.
In Python, what is the purpose of the
break statement in a loop?
A:
Skips the remaining code in the loop and moves to the next iteration.
B:
Exits the loop prematurely.
C:
Repeats the loop indefinitely.
D:
Jumps to the next loop iteration.
Answer: B
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.Discuss About this Question.
Which of the following is the correct syntax to define an infinite loop?
A:
for i in range(10):
B:
while True:
C:
while False:
D:
for i in range(1, 0, -1):
Answer: B
while True: creates an infinite loop, as the condition is always true.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.