OCJP

Iteration in Python :Python Loops (While, For)

Like in other programming languages python also support iterations using While and For. Like C,C++,Java, C# Python does not support Do.While. But you can achieve this type of exit control loop using while.

Following Example explains the Loops in Python

#Loops in Python

i=1
while(i<=10):
    print(i)
    i+=1
    

#There is no Do.while in Python but can be achived as


i=11
while(True):
    print(i)
    if i>=15:
        break
    i+=1

#For Loop

for i in range(10): #0 to 9
    print(i)


for i in range(11,16):   #11 to 15
    print(i)


for i in range(10,51,5):  # 10,15,20..50
    print(i)


for i in range(100,89,-1):  #100 to 90
    print(i)

for i in range(1,50):   # 1,3,5,7, 
    if i%2 ==0 :
        continue
    print(i)
#for else
for x in range(6):
  print(x)
else:
  print("Finally finished!")

Output for the Above Program will be like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
0
1
2
3
4
5
6
7
8
9
11
12
13
14
15
10
15
20
25
30
35
40
45
50
100
99
98
97
96
95
94
93
92
91
90
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
0
1
2
3
4
5
Finally finished!

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?