Iterative statements: In some programs, certain set of
statements are executed again and again based
upon conditional test. i.e executed more than one time. This
type of execution is called looping or
iteration. Looping statement in python is implemented by
using 'for' and 'while' statement.
Syntax: (for loop)
for variable in range(start,stop+1,step):
statements
Syntax: (while loop)
while (condition):
Statements
Example:
1. Write a program to input any number and to print all
natural numbers up to given number.
Code:
n = input("enter any number")
for i in range(1,n+1):
print i,
Output:
enter any number10
1 2 3 4 5 6 7 8 9 10
2. Write a program to input any number and to find sum of
all natural numbers up to given number.
Code:
n = input("Enter any number")
sum= 0
for i in range(1,n+1):
sum = sum+i
print "sum=",sum
Output:
Enter any number5
sum = 15
3. Write a program to input any number and to find reverse
of that number.
Code:
n = input("Enter any number")
r = 0
while(n>0):
r = r*10+n%10
n = n/10
print "reverse number is", r
Output:
>>>
Enter any number345
reverse number is 543
>>>
Example: Write the output from the following code:
1. sum = 0
for i in range(1,11,2):
sum+ = i
print "sum = ", sum
output:
sum = 25
2. sum = 0
i = 4
while (i<=20):
sum+=i
i+= 4
print "Sum = ",sum
output:
Sum = 60
Example: Interchange for loop into while loop
1. for i in range(10,26,2):
print i
Ans:
i=10
while(i<26):
print i
i+=2
2. s=0
for i in range(10,50,10):
s + =i
print " Sum= ", s
Ans:
s = 0
i = 10
while(i<50):
s+ = i
i+ = 10
print "Sum=",s
Example: Interchange while loop in to for loop.
i = 5
s = 0
while (i<25):
s+ = i
i + = 5
print " Sum =", s
Ans:
s = 0
for i in range(5,25,5):
s+=i
print "Sum = ", s
No comments:
Post a Comment