What is the output of the following code? for i in range(2, 6): print(i)
a) 2 3 4 5
b) 2 3 4 5 6
c) 3 4 5 6
d) 2 4 6
Answer:
a) 2 3 4 5
Explanation:
The code for i in range(2, 6): print(i)
uses the range()
function to generate numbers from 2 to 5. The range()
function generates a sequence starting at 2 (inclusive) and ending at 6 (exclusive), so the loop iterates over 2, 3, 4, and 5.
for i in range(2, 6):
print(i) # Prints 2, 3, 4, 5
This example demonstrates how the range()
function’s start and stop parameters work. The stop parameter is exclusive, meaning the sequence ends before reaching the stop value.
Understanding how range()
works with for
loops is important for controlling loop iterations and managing sequences in Python.