Python Loop

Hello all, in this section of the tutorial we will see in depth about Python loops.

The major Python loops are while loop and for loop.

In this session we will be also seeing nested loops and use of continuous and break statement used in this loop.


It is important to understand what this loop means?

While Loop

Will be seeing this with an example.

Imagine a teacher wants to distribute chocolates from the jar among the students.

she or he can distribute the chocolates one at a time and till all the chocolates from the jar
has distributed.
This means that as long as the condition of chocolates present in jar is true,
he or she will distribute chocolates among the students.

Algorithm

Step 1: number of chocolates in the jar.
 step 2: while number of chocolates in the jar is greater than zero
 step 3: take the chocolate from the jar
 step 4: distribute the chocolate.
step 5: go to step 2
Step 5: stop distribution.

In this example you may have noticed that step 3 to step 5 is executed only when step 2 condition
is true. If the condition is false then the program will automatically come out of loop i.e; step 6.

Now we will see how the above algorithm can be executed in Python shell using while loop.

Syntax of while loop:

while condition:
           statement(s)
statement(s)

Algorithm implementation

Number_of_chocolates = 10
while Number_of_chocolates > 0:
          Number_of_chocolates = Number_of_chocolates -1
          print("Distribute the chocolate")
print("All the chocolates are distributed")


  • Here value of number of chocolates is 10
  • While condition will check the value of number of chocolates is greater than zero or not.
  • When this condition is true the statement under while loop that is tab will be executed.
  • The statement which are not tab will be out of the loop
  • If the condition given in while remains always true, the the loop is called Infinite while loop.
In Python shell we will see implementation of this code but we will take input from the user.

Python Loop, while loop
While Loop
 #example for while loop


user_input = input("Number of chocolates in jar") #input from user

Number_of_chocolates = int(user_input)#converting string into integer

Chocolate_distributed = 0 #How many chocolates distributed each time

while Number_of_chocolates > 0:

          Number_of_chocolates = Number_of_chocolates -1

          Chocolate_distributed = Chocolate_distributed + 1

          print("chocolate Distribute number = ",Chocolate_distributed)

print("All the chocolates are distributed")


  • We take the input from user for number of chocolates in jar.
  • As we know input function always gives a string value, that is converted into integer by using int datatype.
  • Chocolate_distributed variable is defined so see how many chocolate is distributed all the time.
  • while loop is executed till Number_of_chocolates > 0 condition is true.
  • Every time loop is executed value in variable Number_of_chocolates is reduced by 1 and Chocolate_distributed variable is increased by 1 to check the iteration every time.
  • When the while loop condition becomes false i.e; when Number_of_chocolates variable becomes equal to zero, last print statement is executed.

For Loop

For Loop is used in two different situations.

  • When you want to go over every item in a sequence
  • When you want to repeat some action for given number of times.
Lets understand this with an example:

Imagine there is one bookshelf and you have to take a look at each book and write its title on a piece of paper.

In this case you may think bookshelf has a list of sequence of book (item)  and you have to do something with each item.

Example for second situation: When you want to repeat a task n number of times.

Think you have to set a counter which counts till 10.

You can use for loop to increment the value of counter at every clock pulse.

Syntax:

for iteration_variable in sequence :
      statement(s)
statement(s)

Lets implement one example in Python shell


For Loop in Python, Python for loop, Python loop
For Loop in Python

#example of for loop

my_book = ["Python","C#","C++","Java"]
for x in my_book:
    print(x)

print("No more books on shelf")


  • In above example we have declared a list names my_book, which has list of 4 books, assuming they are the books in shelf on which action is to perform.
  • When for loop starts executing it assign x to each value in my_bool list.
  • First print statement will print value of x.
  • This loop is executed till x is assign to last list content.
  • At the end it will print last statement which is not tab, because it doesn't come under for loop.
Take another example of counter will you have to count clock pulses


#example of for loop

counter = 0
for x in range(1,11):
    counter = counter + 1
    print("clock_pulse counted are", counter)
print("End of counter")


  • Try above example and you will see "clock_pulse counted are" are executed as for loop uses range value.
  • The range is a function that starts with start number and ends at last number minus 1
  • In this x is assign to each number in range function and for loop is executed for that many times.
Try implementing below question in your IDLE:


Question: Using a for loop, write a program which asks the user to type a positive integer, n, and then prints the sum of the square of all numbers form 1 to n (including both 1 and n).
For example if the user type 3, the answer should be ((3**2) + (2**2) + (1**2)) = 14

Continue and Break Statement 

Sometime it is necessary to terminate current while or for loop. In this cases we can use Continue and break statement.

The continue statement is used to skip the rest of code instead of loop for current iteration only.
The loop does not terminates but continues on the next iteration.

The break statement terminates the loop and jumps to the next statement after the Loop.

Example:

Python Loop, Continue and Break Statement in Python
Continue and Break Statement in Python
Output:
Python Loop, Continue and Break Statement in Python
Continue and Break Statement in Python
#program without using continue or Break Statement

for char in "Pythonior":
    print(char)

print("for loop completed \n")

#Program using for loop and continue statement

for char in "Pythonior":
    if char == "n" :
        continue
    print(char)
    
print("for loop completed with use of continue statement \n")

#Program using for loop and break statement

for char in "Pythonior":
    if char == "n" :
        break
    print(char)
    

print("for loop completed with use of break statement \n")

  • You may see in first part of program all the character values in "Pythonior" is printed in the output screen.
  • As it does not use continue or break statement.
  • In second part of program we have used continue statement along with if statement.
  • You may see in output all the character in "Pythonior" excluding 'n' is printed.
  • This happens because of if statement. if statement becomes true when char value is 'n' and in if loop only a continue statement is noted nothing else. So, you are actually breaking the iteration and compiler jumps to for loop after continue statement, and starts executing.
  • In third part we have used break statement. This program also works as previous one, but when break statement is executed instead of going to execute for loop compiler comes out of all the loops and starts executing next statement. 
Hope you have understood Continue and Break statements use and How to use it in your code.

With this lets see last part of this session: 

Nested Loop

Same as nested if statement we can also use nested loops.

Any loop can be nested in any other loop.

Syntax of for loop:

for var_1 in seq_1:
       statement(s)
      for var_2 in seq_2:
            statement(s)
statement_outside_loop

Syntax of while loop:

while condition:
           statement(s)
           while condition:
                    statement(s)
statement(s)

Syntax having different loop:

for var_1 in seq_1:
         statement(s)
         while condition:
                   statement(s)
statement(s)

Example:

m = 0
x = 1
while x < 4:
    y = 1
    while y < 5:   
        m = m + y
        y = y + 1
        if x + y == 5:
            break
    x = x + 1

print (m)

Above given is very simple code for nested while loops.

  • As you see the code you can observe that outer while loop is executed only when condition x less than 4 becomes true, as x becomes greater than 4 condition becomes false and it comes out of all the loops.
  • Second while loop, which is nested under an outer while is executed when condition of outer while loop is true and y is less than 5, when y becomes greater than 5 program will come out of second while loop and starts executing statements out of it.
Similarly you can use nested loops when one condition is depended on another.

I hope all the points under Python Loop are understood. 

You can mail me if you have any doubts or question on abolikhedkar@gmail.com.

Thank you.


Comments

Popular Post

Python Data Types

Python String

Python List