top

Search

Python Tutorial

Any computer program follows by default a sequential flow of execution of statements. Sometimes, the program flow may skip some statements as in the use of if – elif- else statements. If the program flow is directed towards any of earlier statements in the program, it constitutes a loop.In above diagram, after execution of statement4, normally statement5 would have been executed. However, the control is directed to an earlier statement1. Hence, the section from statement1 to statement4 will be repeated and will keep repeating.Sending the program control to earlier statement unconditionally causes infinite loop, which is not desired. Python uses while and for keywords to constitute conditional loop by which repeated execution of a block of statements is done until a Boolean expression is true.In above diagram, if <expr> is true, the block (statement1, statement2, statement3) will be executed repeatedly as long as it is true. As soon as it doesn’t remain true, flow of the process comes out of loop and default path of program is undertaken.while loopwhile statement in python implements above algorithm.General usage of while statement is as below:while expr==True:    stmt1    stmt2    stmt3 stmt4Here while statement is followed by a conditional expression and ends with : symbol which starts a block with increased indent. In this block statements to be executed repeatedly are entered. Such block is usually called body of loop. Repeated execution continues till the condition remains true. As and when it becomes false, repetition stops and subsequent statements at previous indent level will be executed.Let us develop a Python program that successively takes number as input from user and calculates average of numbers as long as user enters any positive number. Here, the body of loop comprises input statement, statement to add input number and count number of input.num=0 count=0 sum=0 while num>=0:    num=int(input("enter any number .. -1 to exit\n"))    if num>=0:        count=count+1 # this counts number of inputs        sum=sum+num # this adds input number cumulatively. avg=sum/count print ("numbers input:",count, "average:",avg)As soon as a negative number is given, the loop terminates and displays average.enter any number .. -1 to exit 10 enter any number .. -1 to exit 20 enter any number .. -1 to exit 30 enter any number .. -1 to exit -1 numbers input: 3 average: 20.0for loopPython’s for keyword provides is mainly useful to iterate through items in sequence object. The body of the loop is executed for each member element in a sequence. No other Boolean expression is required to control the loop.General usage of for statement in Python is as below:for x in sequence:    stmt1    stmt2    stmt3    stmt4The loop starts with variable x set to item at 0th index in the sequence. Statements with increased uniformly indented block after : symbol will be executed. Variable x now refers to each subsequent item and body of loop keeps on getting executed till the sequence is exhausted.Using range() In Python, range object is an immutable sequence of numbers. It is useful in keeping count of repetition of a block in for loop. The range() function is used as follows:range([start], stop, [step])All three parameters have to be integer. Value of [start] parameter is 0 by default, unless given other integer. The only mandatory parameter for above function is stop. Last number in sequence is one less than stop parameter. Numbers in between are incremented with [step] value, which is 1 by default.For example:range(10) will generate 0,1,2,3,4,5,6,7,8,9range(1,5) will generate 1,2,3,4range(20,30,2) will generate 20,22,24,26,28We can run for loop over a range. To print each number in given rangefor num in range(1,11):    print (num) print ("end of sequence")Above code prints following output.1 2 3 4 5 6 7 8 9 10 end of sequenceFollowing code calculates factorial value of a number taken as input.Factorial of a certain number is product of all numbers between 1 and itself. We use range() function to obtain the sequence. Body of for loop performs cumulative multiplication of all numbers in the range.num=int(input("enter a number")) fact=1 for x in range(1,num+1):    fact=fact*x print ("factorial of {} is {}".format(num,fact))Sample run of above code shows factorial of 4 enter a number4 factorial of 4 is 24As mentioned above, for loop iterates over elements in any sequence. We shall now learn to use for statement with sequence data types – string, list and tuple. for loop over string for char in " KnowledgeHut": print (char)Above example prints one character of given string at a time.K n o w l e d g e H u tfor loop over list / tupleList and tuple object is also a sequence. If each item in list/tuple is to be processed, for statement is very much suitable. Following code computes average of all numbers in a list.sum=0 numbers=[10,20,30,40] for num in numbers:        sum=sum+num avg=sum/len(numbers) print ('average:', avg)Output:average: 25.0for loop on dictionary objectPython’s dictionary is an unordered collection of Key-value pair items which do not have index. The for statement offers a convenient way to traverse a dictionary object. The items() method of  dictionary object returns a list of tuples, each tuple having key and value corresponding to each item. We know that for loop can iterate through tuple. Following code uses for statement to print all key value pairs indict={1:100, 2:200, 3:300} for pair in dict.items():    print (pair)Following output will be displayed on Python console(1, 100) (2, 200) (3, 300)You can unpack each pair tuple to two variables in for statement to get key and value separately.dict={1:100, 2:200, 3:300} for k,v in dict.items():    print (k,v)Output :1 100 2 200 3 300The keys() and values() methods of dictionary object also return list of keys and values from dictionary respectively. We can use them and iterate over each key/value using for loop.dict={1:100, 2:200, 3:300} for k in dict.keys():     print (k,dict.get(k))Using else with loopJust as with if statement, Python allows else keyword to be used with for and while statements too. The else block appears after the body of the loop. The else block will be executed only after all iterations are completed. Program leaves the loop only after else block is executed.for x in range(5):        print ("iteration no ", x+1) else:        print ("in else block in loop") print ("end of loop")Output of above code confirms that else block in for loop will be executed when numbers in range are over.iteration no 1 iteration no 2 iteration no 3 iteration no 4 iteration no 5 in else block in loop end of loopUse of else works well with while loop too.x=0 while x<=5:        x=x+1        print ("iteration no ",(x+1) else:        print ("This is last statement in loop") print ("end of loop")Loop ControlNormally, a loop (while or for) is employed for a certain number of repetitions of a block. The number of repetitions is decided by while condition. Length of sequence (string, list, tuple etc.) determines iterations of for loop.However, sometimes it is required that the loop be abandoned before completing stipulated number of iterations. You may also want next iteration to start before actually completing the current round of execution of body of the loop.Python’s break and continue keywords for these purposes respectively. They act as loop control statements.break keyword:When this keyword is used in the middle of a loop, it abandons pending iterations of current loop and control of program jumps to the statement immediately after the body of the loop.Typical use of break is found where you need to search for an object in a collection. You will have to execute comparison expression in a loop. However, if the required object is found, since there is no need to traverse remaining collection, remaining loop iterations are skipped using break statement.Following diagram shows exact scenario.In above diagram, looping block will be repeatedly executed till expression1 is true. However, inside the looping block, there is another expression2 which is verified for each iteration. As soon as it is found to be true, program control breaks out of the loop.Python has break keyword to implement this functionality. General usage of break inside a while loop is as follows:while expression1==True:        statement1        if expression2==True:                break        statement2 statement3Usage of break within for loop is shown as below:for x in sequence:        statement1        if expression==True:                break        statement2 statement3Following program demonstrates use of break in a loop. It accepts a number as input and determines whether it is a prime number or not. By definition, n is prime if it is not divisible by any number between the range 2 to n-1.The for loop reads one number from the range at a time as x and checks whether it divides n. If n%x returns 0, n is not prime and it is not necessary to check it for remaining numbers and loop needs to be terminated after displaying the message to that effect. It is done by break statement.On the other hand if no number in the range is able to divide n, it is a prime number. Appropriate message is printed in else block.num=int(input("enter a number")) for x in range(2,num):        if num%x==0:                print ("{} is not prime".format(num))                break else:        print ("{} is prime".format(num))Output:enter a number46 46 is not prime enter a number12 12 is not prime enter a number7 7 is prime enter a number29 29 is primeContinue keywordThe continue statement works exactly opposite to that of break. Instead of leaving the loop, continue statement skips remaining statements in current loop and starts next iteration. Following diagram shows how continue works.When expression in the loop (expression2) is true remaining statements in the current will be skipped and program control starts next round of iteration.Usage of continue in Python is as below:while expression1==True:    statement1    if expression2==True:        continue    statement2 statement3Similarly, continue statement is used in for loop as below:for x in sequence:    statement1    if expression==True:        continue    statement2 statement3Following program uses continue keyword. User is asked to input a number till it is found to be even.count=0 while True:        count=count+1        n=int(input("Enter a number"))        if n%2!=0:                continue        print ("Got an even number on attempt no. {}".format(count))        breakOutput:Enter a number1 Enter a number3 Enter a number2 Got an even number on attempt no. 3pass keywordThe  pass keyword is used as a nominal placeholder whenever a certain statement is required but it is not expected to do anything. Python interpreter treats it as a null statement. It is generally used as a dummy statement in a conditional code block.if expression:         passThe pass statement is generally used by programmers to design code framework. Initially the programmer will create no operation blocks using pass and eventually fill their functionality.Nested LoopsIf a loop (for loop or while loop) contains another loop in its body block, the two loops are nested. If outer loop is designed to perform x iterations and inner loop is designed to perform y repetitions, body block of inner loop will get executed x X y times.for x in range(2):        for y in range(2):                print ("x={} y={}".format(x,y))Here outer loop controlled  by x will have two values (0,1) and y controlling inner loop also takes two values (0,1). Hence there will be four iterations of innermost statement.x=0 y=0 x=0 y=1 x=1 y=0 x=1 y=1In this chapter, Python keywords related to looping mechanism have been described.
logo

Python Tutorial

Python - Loops

Any computer program follows by default a sequential flow of execution of statements. Sometimes, the program flow may skip some statements as in the use of if – elif- else statements. If the program flow is directed towards any of earlier statements in the program, it constitutes a loop.python structure

In above diagram, after execution of statement4, normally statement5 would have been executed. However, the control is directed to an earlier statement1. Hence, the section from statement1 to statement4 will be repeated and will keep repeating.
Sending the program control to earlier statement unconditionally causes infinite loop, which is not desired. Python uses while and for keywords to constitute conditional loop by which repeated execution of a block of statements is done until a Boolean expression is true.python structure

In above diagram, if <expr> is true, the block (statement1, statement2, statement3) will be executed repeatedly as long as it is true. As soon as it doesn’t remain true, flow of the process comes out of loop and default path of program is undertaken.

while loop

while statement in python implements above algorithm.

General usage of while statement is as below:

while expr==True:
   stmt1
   stmt2
   stmt3
stmt4

Here while statement is followed by a conditional expression and ends with : symbol which starts a block with increased indent. In this block statements to be executed repeatedly are entered. Such block is usually called body of loop. Repeated execution continues till the condition remains true. As and when it becomes false, repetition stops and subsequent statements at previous indent level will be executed.

Let us develop a Python program that successively takes number as input from user and calculates average of numbers as long as user enters any positive number. Here, the body of loop comprises input statement, statement to add input number and count number of input.

num=0
count=0
sum=0
while num>=0:
   num=int(input("enter any number .. -1 to exit\n"))
   if num>=0:
       count=count+1 # this counts number of inputs
       sum=sum+num # this adds input number cumulatively.
avg=sum/count
print ("numbers input:",count, "average:",avg)

As soon as a negative number is given, the loop terminates and displays average.

enter any number .. -1 to exit
10
enter any number .. -1 to exit
20
enter any number .. -1 to exit
30
enter any number .. -1 to exit
-1
numbers input: 3 average: 20.0

for loop

Python’s for keyword provides is mainly useful to iterate through items in sequence object. The body of the loop is executed for each member element in a sequence. No other Boolean expression is required to control the loop.

General usage of for statement in Python is as below:

for x in sequence:
   stmt1
   stmt2
   stmt3
   stmt4

The loop starts with variable x set to item at 0th index in the sequence. Statements with increased uniformly indented block after : symbol will be executed. Variable x now refers to each subsequent item and body of loop keeps on getting executed till the sequence is exhausted.

Using range() 

In Python, range object is an immutable sequence of numbers. It is useful in keeping count of repetition of a block in for loop. The range() function is used as follows:

range([start], stop, [step])

All three parameters have to be integer. Value of [start] parameter is 0 by default, unless given other integer. The only mandatory parameter for above function is stop. Last number in sequence is one less than stop parameter. Numbers in between are incremented with [step] value, which is 1 by default.

For example:

range(10) will generate 0,1,2,3,4,5,6,7,8,9

range(1,5) will generate 1,2,3,4

range(20,30,2) will generate 20,22,24,26,28

We can run for loop over a range. To print each number in given range

for num in range(1,11):
   print (num)
print ("end of sequence")

Above code prints following output.

1
2
3
4
5
6
7
8
9
10
end of sequence

Following code calculates factorial value of a number taken as input.

Factorial of a certain number is product of all numbers between 1 and itself. We use range() function to obtain the sequence. Body of for loop performs cumulative multiplication of all numbers in the range.

num=int(input("enter a number"))
fact=1
for x in range(1,num+1):
   fact=fact*x
print ("factorial of {} is {}".format(num,fact))

Sample run of above code shows factorial of 4 

enter a number4
factorial of 4 is 24

As mentioned above, for loop iterates over elements in any sequence. We shall now learn to use for statement with sequence data types – string, list and tuple. 

for loop over string 

for char in " KnowledgeHut":
print (char)

Above example prints one character of given string at a time.

K
n
o
w
l
e
d
g
e
H
u
t

for loop over list / tuple

List and tuple object is also a sequence. If each item in list/tuple is to be processed, for statement is very much suitable. Following code computes average of all numbers in a list.

sum=0
numbers=[10,20,30,40]
for num in numbers:
       sum=sum+num
avg=sum/len(numbers)
print ('average:', avg)

Output:

average: 25.0

for loop on dictionary object

Python’s dictionary is an unordered collection of Key-value pair items which do not have index. The for statement offers a convenient way to traverse a dictionary object. The items() method of  dictionary object returns a list of tuples, each tuple having key and value corresponding to each item. We know that for loop can iterate through tuple. Following code uses for statement to print all key value pairs in

dict={1:100, 2:200, 3:300}
for pair in dict.items():
   print (pair)

Following output will be displayed on Python console

(1, 100)
(2, 200)
(3, 300)

You can unpack each pair tuple to two variables in for statement to get key and value separately.

dict={1:100, 2:200, 3:300}
for k,v in dict.items():
   print (k,v)

Output :

1 100
2 200
3 300

The keys() and values() methods of dictionary object also return list of keys and values from dictionary respectively. We can use them and iterate over each key/value using for loop.

dict={1:100, 2:200, 3:300}
for k in dict.keys():
    print (k,dict.get(k))

Using else with loop

Just as with if statement, Python allows else keyword to be used with for and while statements too. The else block appears after the body of the loop. The else block will be executed only after all iterations are completed. Program leaves the loop only after else block is executed.

for x in range(5):
       print ("iteration no ", x+1)
else:
       print ("in else block in loop")
print ("end of loop")

Output of above code confirms that else block in for loop will be executed when numbers in range are over.

iteration no 1
iteration no 2
iteration no 3
iteration no 4
iteration no 5
in else block in loop
end of loop

Use of else works well with while loop too.

x=0
while x<=5:
       x=x+1
       print ("iteration no ",(x+1)
else:
       print ("This is last statement in loop")
print ("end of loop")

Loop Control

Normally, a loop (while or for) is employed for a certain number of repetitions of a block. The number of repetitions is decided by while condition. Length of sequence (string, list, tuple etc.) determines iterations of for loop.

However, sometimes it is required that the loop be abandoned before completing stipulated number of iterations. You may also want next iteration to start before actually completing the current round of execution of body of the loop.

Python’s break and continue keywords for these purposes respectively. They act as loop control statements.

break keyword:

When this keyword is used in the middle of a loop, it abandons pending iterations of current loop and control of program jumps to the statement immediately after the body of the loop.

Typical use of break is found where you need to search for an object in a collection. You will have to execute comparison expression in a loop. However, if the required object is found, since there is no need to traverse remaining collection, remaining loop iterations are skipped using break statement.

Following diagram shows exact scenario.python structure

In above diagram, looping block will be repeatedly executed till expression1 is true. However, inside the looping block, there is another expression2 which is verified for each iteration. As soon as it is found to be true, program control breaks out of the loop.

Python has break keyword to implement this functionality. General usage of break inside a while loop is as follows:

while expression1==True:
       statement1
       if expression2==True:
               break
       statement2
statement3

Usage of break within for loop is shown as below:

for x in sequence:
       statement1
       if expression==True:
               break
       statement2
statement3

Following program demonstrates use of break in a loop. It accepts a number as input and determines whether it is a prime number or not. By definition, n is prime if it is not divisible by any number between the range 2 to n-1.

The for loop reads one number from the range at a time as x and checks whether it divides n. If n%x returns 0, n is not prime and it is not necessary to check it for remaining numbers and loop needs to be terminated after displaying the message to that effect. It is done by break statement.

On the other hand if no number in the range is able to divide n, it is a prime number. Appropriate message is printed in else block.

num=int(input("enter a number"))
for x in range(2,num):
       if num%x==0:
               print ("{} is not prime".format(num))
               break
else:
       print ("{} is prime".format(num))

Output:

enter a number46
46 is not prime
enter a number12
12 is not prime
enter a number7
7 is prime
enter a number29
29 is prime

Continue keyword

The continue statement works exactly opposite to that of break. Instead of leaving the loop, continue statement skips remaining statements in current loop and starts next iteration. Following diagram shows how continue works.python structure

When expression in the loop (expression2) is true remaining statements in the current will be skipped and program control starts next round of iteration.

Usage of continue in Python is as below:

while expression1==True:
   statement1
   if expression2==True:
       continue
   statement2
statement3

Similarly, continue statement is used in for loop as below:

for x in sequence:
   statement1
   if expression==True:
       continue
   statement2
statement3

Following program uses continue keyword. User is asked to input a number till it is found to be even.

count=0
while True:
       count=count+1
       n=int(input("Enter a number"))
       if n%2!=0:
               continue
       print ("Got an even number on attempt no. {}".format(count))
       break

Output:

Enter a number1
Enter a number3
Enter a number2
Got an even number on attempt no. 3

pass keyword

The  pass keyword is used as a nominal placeholder whenever a certain statement is required but it is not expected to do anything. Python interpreter treats it as a null statement. It is generally used as a dummy statement in a conditional code block.

if expression:
        pass

The pass statement is generally used by programmers to design code framework. Initially the programmer will create no operation blocks using pass and eventually fill their functionality.

Nested Loops

If a loop (for loop or while loop) contains another loop in its body block, the two loops are nested. If outer loop is designed to perform x iterations and inner loop is designed to perform y repetitions, body block of inner loop will get executed x X y times.

for x in range(2):
       for y in range(2):
               print ("x={} y={}".format(x,y))

Here outer loop controlled  by x will have two values (0,1) and y controlling inner loop also takes two values (0,1). Hence there will be four iterations of innermost statement.

x=0 y=0
x=0 y=1
x=1 y=0
x=1 y=1

In this chapter, Python keywords related to looping mechanism have been described.

Leave a Reply

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

Comments

Eula

This is my first time here. I am truly impressed to read all this in one place.

Jaypee Dela Cruz

Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!

lucky verma

Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.

Pre Engineered Metal Building

Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.

Pre Engineered Metal Building

Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More