Monday, 27 May 2019

for loop

for loop:
If we want to execute some action for every element present in some sequence.
Syntax:
for variable in sequence:
  body
note: sequence means string,list,set,tuple or any other collections.

Note:

for is a keyword, followed by a variable, for loop contains the keyword 'in'  and specification of a range.
For loop statements executed repeatedly with the variable assuming all values inside range.

Assignment:

Find the factorial of a given number using for loop:
prod=1
n=int(input("enter any no"))
for i in range(1,n+1):
    prod=prod*i
print(prod)

"""output:
enter any no3
6

>>> """

Display in reverse order by using for loop:
>>> for a in range(10,0,-1):
            print(a)
output:10 9 8 7 6 5 4 3 2 1
>>> 

#wap perfect number or not?: Sum of the given no must be equal to given no
n=int(input("enter any no"))
sum=0
for i in range(1,n):
    if n%i==0:
        sum=sum+i
if n==sum:
    print("it is perfect no")
else:
    print("it is not perfect no")
"""output:
enter any no6
it is perfect no
>>> """

#wap to display the elements of a list
a=[10,2.5,'s','kadapa']
#display each element from the lsit
for i in a:
    print(i)
output:  10 2.5 s kadapa
>>> 

#sum of a list numbers using for loop:
a=[10,20,30]
sum=0
print(a)
for i in a:
    sum=sum+i
print(sum)

"""output:
[10, 20, 30]
60

"""

Next Topic:while loop
Previous Topic:Loops in Python

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...