-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython for loop.py
154 lines (112 loc) · 1.88 KB
/
python for loop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#########################################
# #
# #
# Python FOR LOOP #
# #
# #
#########################################
# for loop
# for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
for x in range(11) :
print(x)
# the o/p as will print
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# printing even numbers using for loop
for x in range(11) :
if x % 2 == 0 :
print(x)
# the o/p as
# 2
# 4
# 6
# 8
# 10
# printing odd numbers using for loop
for x in range(11):
if x % 2 != 0 :
print(x)
# the o/p as
# 1
# 3
# 5
# 7
# 9
#################################################
# continue statement
for x in range(11) :
if x % 5 == 0 :
continue
print(x)
# the o/p as
# 1
# 2
# 3
# 4
# 6
# 7
# 8
# 9
# it won't print 5 and 10 becoz we stop it and continue the loop
# we can print it with min range to max range
# for e.g.,
for x in range(5 , 11 ):
print(x)
# the o/p as
# 5
# 6
# 7
# 8
# 9
# 10
# else in for loop
for x in range(5,20,3):
# here min range = 5 , max = 20 and 3 is adding to the next number
print(x)
# finally else
else:
print('loop done')
# the o/p as
# 5
# 8
# 11
# 14
# 17
# loop done
# break
for x in range(10) :
if x == 5 :
break
print(x)
else:
print('loop done')
# the o/p as
# 1
# 2
# 3
# 4
# Note: The else block will NOT be executed if the loop is stopped by a break statement.
#########################################
# nested loop
# A nested loop is a loop inside a loop.
#for e.g
for x in range(1,2) :
for y in range(0,2) :
print(x,y)
# the o/p as
# 1 0
# 1 1
# pass statement in for loop
# for e.g.,
for x in range(0,10) :
pass
# having an empty for loop like this, would raise an error without the pass statement
###############################################################################################