Skip to main content

Looping Constructs-while and for

We know that computers are often used to automate the repetitive tasks. One of the advantages of using computer to repeatedly perform an identical task is that it is done without making any mistake. Loops are used to repeatedly execute the same code in a program. Python provides two types of looping constructs:

1) while statement
2) for statement
Syntax of while
while condition:
            Statement block1
[else:                                       # optional part of while
            Statement block2]
The flow of execution is as follows
1.The condition mentioned in while is evaluated
2.If it is true the statements in the Statement block1 is executed.
( Note that the statements in the body of while must be in the same indent
3.Go back to step1
(Note: The statements in the while loop is executed till the condition
become false )
4.If the condition is false loop is terminated and if the optional else block is present it will be executed followed by the next statement after the while loop is executed.

while loop may not execute even once, if the condition evaluates to false initially, as the condition is tested before entering the loop.
The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.
Eg: Printing 1 to 10 using while loop
while (i <=10):
print  i
i+ =1
print “coming out of loop”

for statement
Syntax is
[else: # optional block

The VARIABLE in for loop will take each value from the list , sequence or string and the loop will continue till the list ends.
Eg: Try the following code
Print 1 2 3 4
for i in 1,2, 3, 4:
           print i,
range() function can be used with for
print 1 to 100
for  i in range(1,101):
           print i,
print even numbers less than 100
for  i in range(2,100,2):
           print i,
for can used to extract characters from strings
for c in “python”:
           print c
The for loop can be used effectively to process lists, strings, files etc..

Lets look at the equivalence of the two looping construct:

i= initial value
while ( i <limit):

for i in range (initial value, limit, step):

Break Statement
Break can be used to jump out of the loop. It terminates the execution of the loop and the next statement after the loop is executed. Break can be used in while loop and for loop. Break is mostly required when because of some external condition, we need to exit from a loop.
for letter in “Python:
if letter = = “h:
print letter
will result into
Continue Statement
This statement is used to tell Python to skip the rest of the statements of the current loop block and to move to next iteration, of the loop. Continue will return back the control to the beginning of the loop. This can also be used with both while and for statement.
for letter in  “Python:
if letter == “h:
print letter
will result into
Sample Programs
Program to find the sum of digits of a number ( university question)
n=input("enter the number..")
while n!=0:
print "sum of the digits=",s
Program to check whether the given number is prime or not ( university question)
n=input("Enter a number..")
while i<=n/2:
    if n%i==0:
if prime==True:
    print 'Prime number'

    print 'Not a prime number'
Program to check whether the given number is prime or not ( university question)
this is written with out using flag variable , using while else
n=input("enter the number..")
while i<=n/2:
    if n%i==0:
        print "Not a prime number.." 
    print "Prime Number.."
Python program to find the sum of even numbers from N given numbers(university question)
N=input("enter the number of numbers (N)..")
print "Enter the ", N ," Numbers"
for i in range(N):
    if num%2==0:
print "Sum of even numbers..",s
Python program to generate n Fibonacci numbers(university question)
n=input("Enter the positive range n.(how many numbers)")
if n==1:
    print a
elif n==2:
    print a,b,
    print a,b,
while i<=n:
    print c,
Write a python program to compute the sum 1+1/2+1/3+-----1/n.Display the result in float with 2 decimal positions. ( University Question)
n=input('Enter n  ')
for i in range(1,n+1):
print("Sum=%0.2f " %s)
Using compound Boolean expression write a Python program to print  the numbers which are divisible by 7 and multiples of 5 between m and n where m and n are positive integers.(university question)
m=input("Enter m...")
n=input("Enter n>m..")
for i in range(m+1,n):
    if (i%7==0 and i%5==0):
         print i,
Write a Python program to print the following output:n=5(uq)
* *
* * *
* *

n=input("Enter number of lines(n)...n must be odd:")
if (n%2!=0):
  for i in range(1,n/2+1):
    print "* "*i
  for i in range(n/2+1,0,-1):
    print "* "*i
Now you can try the following programs using looping constructs while and for
1)Print the even numbers between 0 and 50 (use while)
2)Print the odd numbers between 0 and 50 in the reverse order ( use while)
3)Print the series 5,10,15,….,100 (using for loop)
4)Generate the series 1 2 4 7 11 16....n ( use n)
5)Generate the Fibonacci series 0 1 1 2 3 5 8…..n ( use n)
6)Find the factorial of a number ( use for statement do not use built in factorial() function)
7)Print the powers of a number upto 10th power. ( Eg: if n=2 then the program should print 2**0, 2**1, 2**2,2**3,…..,2**10 use for loop)
8)Print the multiplication table of a given number. ( use while)
9)Print the numbers from 1 to 10 and their natural logarithms as a table ( use for)
10)Find the sum of the digits of a number.( use while-university question)
11)Check whether the given 3 digit number is an Armstrong number. (use while Eg:153,370,371,407)
12)Find the factors of a number ( use for)
13)Check whether the given number is prime or not ( use for)
14) Find the GCD or HCF of two numbers ( use Euclid algorithm and while loop)
15) Reverse a number (use while)
16)Find the numbers between 10 and 1000 that are divisible by 13 but not divisible by 3( use for)
17)Find the sum of series 1-x^2/2+x^4/4-x^6/6........x^n/n ( use while)
18)Check whether the given number is a Krishnamurti number( Krishnamurthy Number: It is a number which is equal to the sum of the factorials of all its digits.Use factorial() function from math
For example : 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145)
19)Read N numbers and find the biggest and smallest. ( university question)
20)Read N numbers and find the sum of all odd and even numbers separately.(university question)
21)Count the number of digits in a number.(university question)
22)Write a Python program to input a list of n numbers. Calculate and display the
sum of cubes of each value in the list.(university question)
23)Write a python program to count the number of zeros and negative terms in a given set of n numbers.
24)Write a python program to input a list of n numbers. calculate and display the average of numbers. Also display the cube of each value in the list.( university question)
25)read mark of n students and print the average mark.Also print the number of students who scored more than 80% mark (mark out of 50)
Nested loops
Python allows one loop to be used inside another loop. For example, block of statement belonging to while can have another while statement i.e. a while statement can contain another while. In this case, the inner while loop will execute completely for each iteration of the outer loop.
while i<=3:
while j<=i:
print j,            # inner while loop

will result into
1 2
1 2 3
In the same way for loop can also be nested
for i in range(1,11):
    for j in range(1,i+1):
        print j,

will print the following
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
We can also nest while and for
i = 6
while i >= 0:
for j in range (1, i):
print j,
will result into
1 2 3 4 5
1 2 3 4
1 2 3
1 2
Nested loop to print all Prime numbers less than 1000 (uq)
for n in range(2,1000):
        while i<=n/2:
                if n%i==0:
                print n,
Nested loop to print the following pattern (uq)        
         5   4  3  2  1
4   3  2  1
3   2  1
2   1
n=input("Enter a number::")
for i in range(n,0,-1):
        for j in range(i,0,-1):
                print j,

Now try the following programs using nested loops
Generate the following pattern
1  2
1 2 3
1 2 3 4
1 2 3 4 5
* * * * *
* * * *
* * *
* *
2 3
4 5 6
7 8 9 10
5 4 3 2 1
4 3 2 1
3 2 1
2 1
15)Print the multiplication table of numbers from 5-15.
6)Print all prime numbers in a given range.
7)Print all 3 digit Armstrong numbers in a range.
8)Print all the factors of numbers between 10 and 20.
9)Print all Armstrong numbers in the given range.
10)Print all Krishnamurti numbers in the given range.
11)Print the sum of digits of all numbers between 100 and 200.
Note: The nested loops are widely used for processing matrix, sorting etc...


Popular posts from this blog

Strings in Python

Strings are compound data type made of sequence of characters. Hence from the string, the individual charters can also be directly accessed. Strings are created by using single quotes or double quotes or triple quotes.
>>>s1="Python Programming"
>>>s2='Python Programs'
>>>s3="""Python is a powerful
Programming language"""

This will create a string object s1, s2 and s3 using different forms.
Individual characters can be accessed using different subscripts( +ve or –ve) with the string object.
We can also slice a string. Segment of a string is called a slice.
If the first index is not mentioned, the slicing will start from 0.
If the last index is not mentioned, the …

Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. The basic components of object oriented programming are classes and objects. A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects. Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions). The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object. Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact. We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects. The class provides basic…

Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc). 
When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name. 
By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well. 
To open a…