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)
n=input("Enter a number..")
i=2
prime=True
while i<=n/2:
    if n%i==0:
        prime=False
        break
    i=i+1
if prime==True:
    print 'Prime number'
else:

    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
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
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  ')
s=0
for i in range(1,n+1):
    t=1.0/i
    s=s+t
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 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
Nested loop to print all Prime numbers less than 1000 (uq)
for n in range(2,1000):
        i=2
        while i<=n/2:
                if n%i==0:
                          break
                i=i+1
        else:
                print n,
Nested loop to print the following pattern (uq)        
         5   4  3  2  1
4   3  2  1
3   2  1
2   1
          1
n=input("Enter a number::")
for i in range(n,0,-1):
        for j in range(i,0,-1):
                print j,
        print 

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




Comments

Popular posts from this blog

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. Th

Identifiers,Variables and Keywords

Identifiers An identifier is a name given to entities like variables,functions,class, functions etc. It helps to differentiate one entity from another. Rules for writing identifiers 1.Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.  Names like myClass, var_1 and print_this_to_screen, all are valid example. 2.An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. 3.Keywords cannot be used as identifiers. Eg: global = 1 is invalid 4.We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@=0 is invalid 5.An identifier can be of any length. Things to Remember Python is a case-sensitive language. This means, Variable and variable are not the same. Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count=10 would make more sense, and it would be easier to figure out what it represents when you look at your code after

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.