World Languages, asked by aganyir18, 1 year ago


1 point
What is the output of the following snippet?
s=0
for s in range(5):
print(s)

Answers

Answered by poojan
10

NOTE :

With a dilemma on 3rd statement (whether it is present in inside the loop or on outside), we are giving both the codes and their outputs. Please check.

Code 1 : (Print statement is written outside the loop)

s=0

for s in range(5):

print(s)

Output :

Indentation Error raises.

Reason :

A loop must consist alteast one statement in it. else, the interpreter considers it as an Indent error thinking that the next statements should be in the loop.

Code 2 : (Print statement in the loop)

s=0

for s in range(5):

     print(s)

Output :

0

1

2

3

4

Explanation :

  • Here, we initialized s with 0. On entering the loop, where the range is mentioned as 5.

  • s in range(5) means range(5) creates a iterable from 0 to 5 excluding 5 as (0, 1, 2, 3, 4) with increment of 1 on every iteration

  • So, on first iteration s is filled with the first element of the iterable which is 0. As now s=0, print(s) prints 0.

  • Then the next value 1 will be stored in s, by incrementation over iteration and then goes into the loop, prints 1.

  • Similarly, the loop runs and prints 2, 3, 4 too.

  • Now, the printed numbers are 0, 1, 2, 3, 4. That means 5 iterations are happened already.

  • On 6th iteration, the value becomes 5 on incremention, which is excluded. As the condition fails, the loop terminates leaving the final output as 0, 1, 2, 3, 4 each printed on a new line.

Learn more :

1. Program to perform Arithmetic operations using function.

brainly.in/question/18905944

2. Write a simple python function to increase the value of any number by a constant "C=5"

brainly.in/question/16322662

Similar questions