You are on page 1of 1

1.

11 Looping Statements

Q1. What will be the output of the following code?

print(range(5))

Ans. The range() function is used to generate a sequence of numbers equidistant from each other. It
takes 3 parameters, start, stop, and step. Stop is a mandatory parameter and by default, start is set
to 0 and step is set to 1. So, range(5) will give the same output as range(0,5).

Q2. What will be the output of the following code?

for i in range(1,5):

print(i*2)

Ans. In this question the variable "i" is used to index the various elements of the range 1 to 5
(exclusive). So with print(i*2) Python will call every element at index location multiply it with 2 and
print the output.

Iteration 1: i = 1, 1 * 2 = 2

Iteration 2: i = 2, 2 * 2 = 4

Iteration 3: i = 3, 3 * 2 = 6

Iteration 4: i = 4, 4 * 2 = 8

Q3. Identify the output of the following code

sum = 0

for number in range(1,5):

sum = sum + number

print(sum)

Ans. 10

Here, the variable "number" is used to iterate over the elements of the range(1,5), which is a
sequence of numbers from 1 to 4 (as 5 is exclusive). For each iteration of the for loop, Python will
add the value stored in the variable number to the variable sum.

Iteration 1: sum = 0 + number = 0 + 1 = 1

Iteration 2: sum = 1 + number = 1 + 2 = 3

Iteration 3: sum = 3 + number = 3 + 3 = 6

Iteration 4: sum = 6 + number = 6 + 4 = 10

Once all the iterations are completed, the final value of the variable sum will be printed.

You might also like