For Loop In Python Language

Watch video presentation here and remember to subscribe to our channel;

Watch now!

In our previous tutorial we discussed while loop, now in this tutorial we will discuss for loop which is the other common type of loop in python language. In this tutorial we will discuss the following;

  • Break statement
  • Continue statement
  • Else statement
  • Nested loops
  • Pass statement

For loop -this type of loop is used to execute block of codes for a specific number of times, but in python is used to execute sequences such as lists, tuple, a set or even a string. For instance, we can execute a set of statements for each item in a list or set.

Let’s have an examples here;

Example 1

cars = ["BMW", "Mercedez", "Toyota"]

for x in cars:

print(x)

Example 2

In this example we will look at how you can iterate through a string;

for x in "Toyota":

print(x)

a) Range() function – range() function is used to loop through codes which have specific number of times, it returns values which starts from zero, then it adds the value by 1 to a specific number. Let’s have an example;

for y in range(6):

print(y)


NB: -Remember you can specify the value where it starts by adding parameters as follows; range(3, 9)
-You can also specify the increment value since it's always set to 1 by default, to add increment value you will as follows; range(3, 9, 2), therefore it will adding the value by 2.

b) Else statement

In this case else statement is used to show the codes which will be executed when the iteration comes to an end.

Let’s have an example here for better understanding;

for x in range(8):

 print(x)

else:

 print("The number is not in range")

c) Nested Loops – in this case we have a loop inside another loop, whereby the inner loop is executed one time for every outer loop iteration. For instance, we may have loops for drivers and cars, therefore you may print cars for each driver.

Look at this example here;

drivers = ["John", "Philloh", "Simon"]

cars = ["BMW", "Toyota", "Ford"]

 for x in drivers:

  for y in cars:
   
   print(x, y)

d) Pass statement – It may come to a situation when a for loop is empty therefore we uses pass to avoid errors when you run your codes. Let’s see this example;

for a in [0, 4, 6]:

pass

e) Break statement – In this case when you use break you can stop the loop before the iteration ended. Let’s have example here;

cars = ["BMW", "Toyota", "Ford", "V8"]

for y in cars:

 print(y)
 
 if y == "Ford":

  break

e) Continue statement – in this case we can stop in a particular iteration of a loop and then start the next iteration. Let’s have an example here;

cars = ["Ford", "Mercedes", "BMW", "V8", "Toyota"]

for y in cars:

 if y == "BMW":

 continue
 
 print(y)

Thanks for reading through our tutorial, as we continue learning python keep updated in our website for more awesome tutorials.