Example-3
#largest of three numbers
n1=input("Enter number 1")
n2=input("Enter number 2")
n3=input("Enter number 3")
large=n1
if n1>=n2 and n1>=n3:
print 'Largest %s'%n1
elif n2>=n1 and n2>=n3:
print 'Largest %s'%n2
else:
print 'Largest %s'%n3
Example -4
#to check whether triangle can be formed and calculate area
print("Enter three sides ")
a=input()
b=input()
c=input()
if a<=0 or b<=0 or c<=0 or c>a+b or b>a+c or a>b+c:
print "Triangle can not be formed "
else:
print "Triangle can be formed"
if a==b==c:
print "Eqilateral triangle"
elif a==b or b==c or c==a:
print "Isoceles triangle"
else:
print "Scalene triangle"
s=(a+b+c)/2.0
area=(s*(s-a)*(s-b)*(s-c))**.5
print "Area = %.4f"%area
Example-5
#roots of a quadratic equation
print "Enter coefficients"
a=float(input("a="))
b=float(input("b="))
c=float(input("c="))
d=b*b-4*a*c
if d==0:
print "Roots are equal"
print "Root= %.4f"% -(b/(2*a))
elif d>0:
print "Roots are real and unequal"
r1=(-b+d**.5)/(2*a)
r2=(-b-d**.5)/(2*a)
print "Root 1= %.4f and Root 2= %.4f"%(r1,r2)
else:
print "Roots are imaginary"
real=-(b/(2*a))
imag=(-d)**.5/(2*a)
print "Root 1= %.4f+j%.4f and Root 2= %.4f-j%.4f"%(real,imag,real,imag)
Example - 6
# print odd numbers in reverse order and calculate sum and average
n=input("Enter n ")
i=1
e=n*2-1
sum=0
while i<=n:
print e
sum=sum+e
e=e-2
i=i+1
average=sum/float(n)
print "Sum = %.2f"%sum
print "Average %.2f"%average
Example - 7
#print even and odd numbers in a range and calculate sum and average
n1=input("Enter lower limit")
n2=input("Enter upper limit")
sum=0
count=0
print "Even numbers"
i=n1
while i<=n2:
if i%2==0:
sum=sum+i
count=count+1
print i
i=i+1
print "Sum = %.2f"%sum
Average=sum/float(count)
print "Average = %.2f"%Average
sum=0
count=0
print "Odd numbers"
for i in range(n1,n2+1):
if i%2==1:
sum=sum+i
count=count+1
print i
print "Sum = %.2f"%sum
Average=sum/float(count)
print "Average = %.2f"%Average
No comments:
Post a Comment