For Loop¶
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
L=[10,20,"Machine Learning",40,50]
for i in L:
print("Printing",i)
The range() Function¶
To loop through a set of code a specified number of times, we can use the range() function
L=list(range(10))
for i in L:
print(i,end=' ')
for i in range(10):
print(i,end=' ')
for i in range(1,10):
print(i,end=' ')
for i in range(1,10,1):
print(i,end=' ')
for i in range(1,10,2):
print(i,end=' ')
for i in range(5):
print("MachineLearning.org.in")
For Loop Control Statement¶
for i in range(1,10):
if i%3==0:
print(i,end=' ')
Looping Through a String¶
Even strings are iterable objects, they contain a sequence of characters:
for x in "python":
print(x)
For Loop with break Statement¶
With the break statement we can stop the loop before it has looped through all the items:
for i in range(1,10):
if i==5:
break
print(i,end=' ')
For Loop with Continue Statement¶
With the continue statement we can stop the current iteration of the loop, and continue with the next:
for i in range(1,10):
if i==5:
continue
print(i,end=' ')
Else in For Loop¶
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested For Loop¶
A nested loop is a loop inside a loop.
The “inner loop” will be executed one time for each iteration of the “outer loop”:
adj = ["Red", "Big", "Tasty"]
fruits = ["Apple", "Watermelon", "Mango"]
for x in adj:
for y in fruits:
print(x, y)
The while Loop¶
With the while loop we can execute a set of statements as long as a condition is true.
i=1
while(i<=5):
print("MachineLearning.org.in")
i=i+1
i = 1
while i <= 10:
print(i,end=' ')
i += 1
The break Statement¶
With the break statement we can stop the loop even if the while condition is true:
i = 1
while i <= 10:
if i==4:
break
print(i)
i += 1
The continue Statement¶
With the continue statement we can stop the current iteration, and continue with the next:
i = 0
while i <= 10:
i += 1
if i==4:
continue
print(i)
The else Statement¶
With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")