Python for Loop
Python for loops are specially used when you want to repeat a block of code a fixed number of times. you can also iterate over a list, a tuple, a dictionary, a set or a string using for loop.
Example:
for i in "computer":
print(i)
Output:
c o m p u t e r
This is an example of looping through a string using for loop.
break Statement
You can break a loop before it has looped through all items using the break statement. If the execution reaches a break statement its immediately breaks the loop and exits from the block of the while loop. A break statement just contains the break keyword.
Example:
cities = ["New York", "London", "Sydney", "Dhaka"]
for i in cities:
print(i)
if i == "Sydney":
break
Output:
New York London Sydney
continue Statement
You can stop a current iteration and continue with the next using the continue statement. If the execution reaches the continue statement its immediately stop the current iteration and continue with the next iteration. A continue statement just contains the continue keyword.
Example:
cities = ["New York", "London", "Sydney", "Dhaka"]
for i in cities:
if i == "Sydney":
continue
print(i)
Output:
New York London Dhaka
range() Function
You can also use the range() function with for loop. By range() function you can set how many times the loop will be occured.
Example:
for i in range(5):
print(i)
Output:
0 1 2 3 4
By default the starting value of a range() function is 0. You can change the starting value using parameter.
Example:
for i in range(2, 5):
print(i)
Output:
2 3 4
You can also specify the increment value using a third parameter.
Example:
for i in range(2, 30, 5):
print(i)
Output:
2 7 12 17 22 27