Loop in Python

0 Comments

Range method returns values between start and stop, increasing by the value of step (defaults to 1)…   range(start, stop, step)

>>> for i in range (0, 10):

… print(i)

File “<stdin>”, line 2

print(i)

^

IndentationError: expected an indented block

Lets fix this with a comma before print statement

for i in range (0, 10):
   print(i)

Output:

0

1

2

3

4

5

6

7

8

9

Number from 0 inclusive to 9 print excluding 10 in the above example

In the below example we will provide a value for step i.e. third parameter of this range method.

for i in range (0, 10,2):
   print(i)

Output:

0

2

4

6

8

Range method can be very useful when starting Python or diving into Data Analysis.

Comparison of Range method with while loop

Without While loop:

for i in range(2, 12, 3):
   print(i)

Output:

2

5

8

11

With While loop:

i=2

while(i<12):
   print(i)
   i+=3

Output:

2

5

8

11

 

Let’s consider another example

 

for i in range(0, 5):
    if i % 3 == 0:
        print(i)
    elif:
       i % 3 == 1print(i+10)
    else:
       print(i-10)

Output:

0

11

-8

3

14

X % y (modulo) produces the remainder from x / y.


Leave a Reply

Your email address will not be published.