For loop is used to iterate items. Use of for loop in the python programming language.
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
for number in range(1, 10, 2):
print(number)
Output:
1
3
5
7
9
a = ['onion', 'potato', 'ginger', 'cucumber']
for item in a:
print(item)
b = {
'name': 'MD. Al-Mamun Sarkar',
'nickname': 'Mamun',
'email': 'mamun@example.com',
'phone': '2345234534'
}
for item in b:
print(item)
break fully stop the loop.
a = ['onion', 'potato', 'ginger', 'cucumber']
for item in a:
if item == 'ginger':
break
print(item)
Output:
onion
potato
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
for i in range(6):
print(i)
else:
print("Loop has been finished.")
Output:
0
1
2
3
4
5
Loop has been finished.
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
for i in [0, 1, 2]:
pass