Python For Loop

In this tutorial you will learn:

  • Loop in Python
  • For loop in Python
  • Nested for loop in Python
  • Break statement in for loop
  • Continue statement in for loop

Loop in Python

In programming we sometimes need to execute a block of code again and again and for that we need to use something called loop. Loop helps us to repeat a block of code do something multiple times until a particular condition is satisfied.

For loop in Python

A for loop in Python iterates over a block of code with a variable. A for loop consists of three parts. Initialization, condition and increment. In initialization part we simply need to initialize a value from where to start the loop, in condition part we need to define the condition when to stop and in increment part we need to tell the value that needs to be incremented on each iteration. In Python for loop is a bit different from other programming languages in a sense that it manages the initialization and increment part for us. Printing a list of numbers would take a long time so let’s see how we can simplify it using for loop

For example:

  1. numbers = [67,85,23,45,6,7,8,2,1]
  2. print("This list contains the following: ")
  3. for number in numbers:
  4. print(number)

So instead of writing to print 9 times we just wrote print once and ran the for loop from the start till the end of number list.

Another good example is to find the sum of all the numbers using for loop

  1. sum = 0
  2. print("Sum of numbers: ")
  3. for number in numbers:
  4. sum+=number
  5. print(sum)

Nested for loop in Python

Loops can be nested at many levels but there is one big disadvantage and that is it increases the computation time of your code by using up most the resources of the hardware in case of large datasets or while executing a complex block of code many number of times. But in some cases they are quite useful such as for printing list of lists.

  1. myLists = [["Testing", 1, "Python"], ["John", "Mike", "Todd"]]
  2. print("\nPrinting elements in list of lists")
  3. for list in myLists:
  4. for listItem in list:
  5. print(listItem)

Break statement in for loop

Break statement is used to stop the execution of a block of code and jump out of it.

  1. print("\nStop the loop if 8 is found in numbers: ")
  2. for number in numbers:
  3. if number==8:
  4. break
  5. print(number)

Continue statement in for loop

This statement is used to skip a loop iteration.

  1. print("\nPrinting without even numbers using continue statement:")
  2. for number in numbers:
  3. if number%2 == 0:
  4. continue
  5. print(number)

Add new comment