Python For Loop

Author: Al-mamun Sarkar Date: 2020-03-25 08:28:21

For loop is used to iterate items. Use of for loop in the python programming language. 

 

Loop in number range:

for number in range(1, 5):
    print(number)

inside range first item is included and the last item is excluded

Output:

1
2
3
4

 

Define increment in the loop:

for number in range(1, 10, 2):
    print(number)

Output:

1
3
5
7
9

 

Loop a list:

a = ['onion', 'potato', 'ginger', 'cucumber']
for item in a:
    print(item)

 

 Loop a list:

b = {
    'name': 'MD. Al-Mamun Sarkar', 
    'nickname': 'Mamun', 
    'email': 'mamun@example.com', 
    'phone': '2345234534'
}
for item in b:
    print(item)

 

Use of break:

break fully stop the loop.

a = ['onion', 'potato', 'ginger', 'cucumber']
for item in a:
    if item == 'ginger':
        break
    print(item)

Output:

onion
potato

 

 Use of continue:

continue is just stop the current iteration of the loop.

a = ['onion', 'potato', 'ginger', 'cucumber']
for item in a:
    if item == 'ginger':
        continue
    print(item)

Output:

onion
potato
cucumber

 

Use else in for loop:

for i in range(6):
  print(i)
else:
  print("Loop has been finished.")

Output:

0
1
2
3
4
5
Loop has been finished.

 

 Use Nested for loop:

one = ["one", "two", "three"]
two = [1, 3, 5, 34]
for i in one:
  for j in two:
    print(i, j)

Output:

one 1
one 3
one 5
one 34
two 1
two 3
two 5
two 34
three 1
three 3
three 5
three 34

 

Use the pass to do nothing:

for i in [0, 1, 2]:
  pass