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..
Let‟s 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
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
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)
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
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
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 51 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,
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
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
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)
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
2)
1 2
1 2 3
1 2 3 4
1 2 3 4 5
2)
* * * * *
* * * *
* * *
* *
*
3)
* * * *
* * *
* *
*
3)
1
2 3
4 5 6
7 8 9 10
4)
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.
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...
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
Post a Comment