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:

  1. for i in "computer":
  2. 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:

  1. cities = ["New York", "London", "Sydney", "Dhaka"]
  2. for i in cities:
  3. print(i)
  4. if i == "Sydney":
  5. 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:

  1. cities = ["New York", "London", "Sydney", "Dhaka"]
  2. for i in cities:
  3. if i == "Sydney":
  4. continue
  5. 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:

  1. for i in range(5):
  2. 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:

  1. for i in range(2, 5):
  2. print(i)

Output:

2
3
4

You can also specify the increment value using a third parameter.

Example:

  1. for i in range(2, 30, 5):
  2. print(i)

Output:

2
7
12
17
22
27