Download our e-book of Introduction To Python
Pallavi Dhotre
3 years ago
python loops - while loop example
#pre-test loop
i=1
while i<4:
print(i)
i+=1
1
2
3
#python loops - while loop example
#post-test loop
i=1
while True:
print(i)
i+=1
if i>4:
break
1
2
3
4
#python loops - for loop example
#for loop without range()
print("Without using range() function")
for i in [1,2,10]:
print(i) #this will print all numbers in the given list
print("using range() function with positive integer as a gap")
for i in range(5,15,3): #using the positive integer as a gap
print(i) # this will print the numbers from 5 to 15 (excluded 15) with a gap of 3
print("using range() function with negative integer as a gap")
for i in range(15,5,-3): #using the negative integer as a gap
print(i) # this will print the numbers from 15 to 5 (excluded 5) with a gap of 3
Without using range() function
1
2
10
using range() function with positive integer as a gap
5
8
11
14
using range() function with negative integer as a gap
15
12
9
6
#python loops - nested loop example
for i in range(5,15,2): #outer loop
while i<10: #inner loop
print(i) # end of the inner loop
break
print("The end") #end of the outer loop
5
7
9
The end
#python loops - nested loop example
for i in range(5,15,2): #outer loop
if i<10: #inner loop
print(i)
else:
print(i+2)
# end of the inner loop
print("The end") #end of the outer loop
5
7
9
13
15
The end