HOW TO USE FOR LOOPS IN PYTHON


A For loop is used to execute a set of statements, once for each item in a list, tuple, set, dictionary, string, or any iterable object, etc.

As shown in below example it will print each fruit available in the list

fruits = ["apple", "banana", "cherry"]
for x in fruits:
 print(x)

output

apple
banana
cherry

The break Statement

The break statement is used to stop the loop before it has looped through all the items as shown below control will exit the loop when x is “banana”

fruits = ["apple", "mango, "cherry"]
for x in fruits:
  print(x)
  if x == "mango":
    break

output

apple
mango

The continue Statement

The continue statement is used to stop the current iteration and continue with the next iteration as shown below in the example result will skip the mango-

fruits = ["apple", "mango", "cherry"]
for x in fruits:
  if x == "mango":
    continue
  print(x)

output

apple
cherry

Nested Loops

We can nest the loop inside the loop for each iteration of the outer loop inner loop will completely iterate over the provided sequence as shown in below example, the “inner loop” will be executed one time for each iteration of the “outer loop”-

fruits1 = ["red", "tasty", "sweet"]
fruits2 = ["apple", "strawberry", "cherry"]
for x in fruits1:
  for y in fruits2:
    print(x, y)

output

red apple
red strawberry
red cherry
tasty apple
tasty strawberry
tasty cherry
sweet apple
sweet strawberry
sweet cherry

The pass Statement

The for loop block cannot be empty, but if there is no content, we can put in the pass statement to avoid getting an error.

for x in [0, 1, 2]:
  pass
Print("We are out of for loop block without any error")

output

We are out of for loop block without any error

Leave a Reply

Your email address will not be published. Required fields are marked *