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
level)
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.

Note:
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
i=1
while (i <=10):
print  i
i+ =1
else:
print “coming out of loop”

for statement
Syntax is
for VARIABLE  in  EXPRESSION-LIST:
STATEMENT BLOCK 1
[else: # optional block
STATEMENT BLOCK 2]

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
          
Note
The for loop can be used effectively to process lists, strings, files etc..

Lets look at the equivalence of the two looping construct:
while

for
i= initial value
while ( i <limit):
     statement(s)
     i+=step

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


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.
Example
for letter in “Python:
if letter = = “h:
break
print letter
will result into
P
y
t
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.
Example
for letter in  “Python:
if letter == “h:
continue
print letter
will result into
P
y
t
o
n
Sample Programs
Program to find the sum of digits of a number ( university question)
s=0
n=input("enter the number..")
while n!=0:
    s=s+n%10;
    n=n/10
print "sum of the digits=",s
Program to check whether the given number is prime or not ( university question)
i=2
n=input("enter the number..")
while i<=n/2:
    if n%i==0:
        print "Not a prime number.." 
        break
    i+=1
else:
    print "Prime Number.."
Python program to find the sum of even numbers from N given numbers(university question)
s=0
N=input("enter the number of numbers (N)..")
print "Enter the ", N ," Numbers"
for i in range(N):
    num=input()
    if num%2==0:
        s=s+num
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)")
a=0
b=1
i=3
if n==1:
    print a
elif n==2:
    print a,b,
else:
    print a,b,
while i<=n:
    c=a+b
    a,b=b,c
    print c,
    i=i+1

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 while...read n)
5)Generate the Fibonacci series 0 1 1 2 3 5 8…..n ( use while..read 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.
Example
i=1
while i<=3:
j=1
while j<=i:
print j,            # inner while loop
j=j+1
print
i=i+1

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

will print the following
1
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
Example:
i = 6
while i >= 0:
for j in range (1, i):
print j,
print
i=i-1
will result into
1 2 3 4 5
1 2 3 4
1 2 3
1 2

1
Now try the following programs using nested loops
Generate the following pattern
1)         1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
2)         * * * * *
* * * *
* * *
* *
*
3)         1
2 3
4 5 6
7 8 9 10

4)Print the multiplication table of numbers from 5-15.
5)Print all prime numbers in a given range.
6)Print all 3 digit Armstrong numbers in a range.

7)Print all the factors of numbers between 10 and 20.
8)Print all Armstrong numbers in the given range.
9)Print all Krishnamurti numbers in the given range.
10)Print the sum of digits of all numbers between 100 and 200.
Note: The nested loops are widely used for processing matrix, sorting etc...
Sample program using nested loop to print all Prime numbers less than 1000
for n in range(2,1000):
        i=2
        while i<=n/2:
                if n%i==0:
                          break
                i=i+1
        else:
                print n,




Popular posts from this blog

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 fil…

User Defined Functions in Python

So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself (built in), but it is also possible for programmer to write their own function(s) and are called User Defined Functions. These functions can then be combined to form a module which can then be used in other programs by importing them.
In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition.
To define a function keyword def is used. After the keyword comes an identifier i.e.name of the function, followed by parenthesized list of parameters and the colon which ends up the line. Next follows the block of statement(s) that are the part of function. A block is one or more lines of code, grouped together so that they are treated as one big sequence of statements while executing. In Python, statements in a block are written with indentation. Usually, a block begins when a li…

Dictionary In Python

Dictionaries are similar to other compound types except that they can use any immutable type as an index. We can refer to a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps a value. The association of a key and a value is called a key-value pair. A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences.
            Dictionaries are mutable.             Dictionaries are unordered. Items in dictionaries are accessed via keys and not via their position. A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs.  Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and…