Python Loops

Loop is a continuous iteration of a block of code to ensure some condition.

It means a group of instructions will execute multiple number of times.

There are following types of loops

Loop Type Description
while loop Repeats a statement or group of statements until a given condition is true. It tests the condition before executing the loop body.
for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for or do..while loop.

While Loop


  1. x=4
  2. while x>1:
  3. print x
  4. x--



For Loop


  list = [1, 2, 3]
  for each_num in list
    print each_num



Loop Control Statements:

Loop control statements change execution from its normal sequence

There are following control statements:

Control Statement Description
break statement Terminates the loop statement and transfers execution to the statement immediately following the loop.
continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
pass statement The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

  1. for letter in '': # for loop Example
  2. print 'Letter :', letter

In the next chapter you are going to learn python