For Loop Usage in Python

Itacen Sabacok | Jan 25, 2022
 1# numerical loop
 2numbers = [1, 2, 3, 4]
 3for num in numbers:
 4  print(num)
 5
 6# get every character in the string
 7someStr = "fire in the hole"
 8for s in someStr:
 9  print(s)
10
11# list loop
12carBrands = ["audi", "bmw", "mercedes", "porsche"]
13for brand in carBrands:
14  print(brand)

Range Function

The range() function returns a sequence of numbers. It starts from 0 (by default) and increments by 1 (by default) and ends at a specified number.

 1# print values from 0 to 3
 2for num in range(4):
 3  print(num)
 4
 5# start with 3 and stop before 10
 6for x in range(3, 10):
 7  print(x)
 8
 9# start with 4 and stop before 20 and increment with 3
10for x in range(4, 20, 3):
11  print(x)
1# another list loop example with range()
2carBrands = ["audi", "bmw", "mercedes", "porsche"]
3for brand in range(len(carBrands)):
4  print(carBrands[brand])

Else Usage

it can be valid when the loop is finished.

1for x in range(5, 25, 4):
2  print(x)
3else:
4  print("The loop is finished")

Continue Usage

Continue to the next iteration. it goes directly to top where loop starts. so when brand is bmw then it never print this brand because print is below of continue.

1carBrands = ["audi", "bmw", "mercedes", "porsche"]
2for brand in carBrands:
3  if brand == "bmw":
4    continue
5  print(brand)

Break Usage

break can be used to stop the loop.

1carBrands = ["audi", "bmw", "mercedes", "porsche"]
2for brand in carBrands:
3  print(brand)
4  if brand == "bmw":
5    break

Nested Loop

 1for x in range(2, 5):
 2  for y in range(x, x*2, 2):
 3    print(y)
 4  print(x)
 5
 6str1 = ["Blue","Red","Green"] 
 7str2 = ["Sprinkles"]  
 8for s1 in str1:
 9  for s2 in str2:
10    print(s1,s2)

Pass Usage

for loops cannot be empty! you can use pass statement to avoid getting an error for empty content.

1for x in ["one","two","three"]:
2  pass