21.Example programs using functions

Write a python function to find the area of a circle.
def circlearea (radius): 
    area=3.14*(radius**2)
    return area
#function call
r=int(input("Enter radius.."))
area=circlearea(r)
print("Area of the circle=",area)

output
Enter radius..2
Area of the circle= 12.56
Compute nCr using a factorial function
def fact(n):
    f=1
    for i in range(1,n+1):
        f=f*i
    return f

print("Program to compute nCr...")
n=int(input("Enter n.."))
r=int(input("Enter r..."))
ncr=fact(n)/(fact(n-r)*fact(r))
print("nCr...",ncr)

output
Program to compute nCr...
Enter n..5
Enter r...3
nCr... 10.0

Python function to extract digits and checks whether all the digits are even or not

def digit(n):
    flag=1
    while n!=0:
        d=n%10
        if d%2!=0:
            flag=0
            break
        n=n//10
    return flag

n=int(input("Enter a number::"))
if digit(n):
    print("All digits are even")
else:
    print("All digits are not even")
           
Menu driven program to implement the following i)check even or odd ii)check number is positive negative or zero iii) generate factors of a number ( university question)
def evenodd(n):
    if n%2==0:
        print("even")
    else:
        print("odd")
def postvnegtv(n):
    if n>0:
        print("+ve")
    elif n<0:
        print("-ve")
    else:
        print("zero")
def  factors(n):
    print ("factors")
    for i in range(1,n+1):
        if n%i==0:
            print (i,end=' ')
while True:
     print("\n....Menu...\n1.even or odd\n2.postv or negtv \n3.factors\n4..exit\n")
     ch=int(input("Enter your choice---"))
     if ch==4:
         break
     n=int(input("Enter a number.."))
     if ch==1:
         evenodd(n)
     if ch==2:
         postvnegtv(n)
     if ch==3:
         factors(n)

Write a Python program to find the value for sin(x) up to n terms using the series
sin(x)=1-x^3/3!+x^5/5!..... (      sin(x) = ((-1)^n/(2n+1)!)x^(2n+1)   )
import math
def sinseries(x,n):
    sine = 0
    for i in range(n):
        sign = (-1)**i
        x=x*(math.pi/180)
        sine = sine + ((x**(2.0*i+1))/math.factorial(2*i+1))*sign
    return sine
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(sinseries(x,n),2))
output:
Enter the value of x in degrees:30
Enter the number of terms:10
0.5
Note: you can replace factorial() function in math module with your own function
Create a function min_max() that takes n numbers as list argument and return the smallest and largest numbers.(university question)
def min_max(l,n):
    small=l[0];
    large=l[0];
    for i in range(1,n):
        if l[i]>large:
            large=l[i]
        if l[i]<small:
            small=l[i]
        return(small,large)
n=int(input('Enter n'))
print('Enter numbers')
l=[]
for i in range(n):
    x=int(input())
    l.append(x)
(small,large)=min_max(l,n)
print("Small=",small," large=",large) 
Write a Python program using function to find the sum of first ‘n’ even numbers and return the result to main program.( university question)
def sum_even(n):
    s=0
    for i in range(2*n+1):
        if i%2==0:
            s=s+i
    return s
sum=sum_even(2)
print(sum)
Write a Python program to create a set of functions that compute the mean, median and mode of a set of numbers. Each function should expect a list of numbers as an argument and return a single number. Each function should return 0 if the list is empty. Include a main function that tests the three functions with a given list. ( university question)

( Hint: Mean: Mean is the average value of a list of numbers.Median: If the number of values in a list is odd, the median of the list is the value at the midpoint when the set of numbers is sorted; otherwise, the median is the average of the two values surrounding the midpoint. Mode: The mode of a list of values is the value that occurs most frequently)

def median(lst):
      n=len(lst)
      lst.sort()
      mid=n//2
      if n%2==1:
         return (lst[mid])
      else:
         return ((lst[mid]+lst[mid-1])/2)

def mean(lst):
      n=len(lst)
      return(sum(lst)/n)
def mode(lst):
      nc={}
      md={}
      for i in lst:
            nc[i]=lst.count(i)
      maxcount=max(nc.values())
      for k in nc:
          if nc[k]==maxcount:
              md[k]=maxcount
      return(md)
lst=[3,3,4,6,2,2,7,8,9]
print("Mean=",mean(lst))
print("Median=",median(lst))
print("Mode=",mode(lst))

Write a python program to find X^Y or pow(X,Y) without using standard function(University Question)
def pow(x,y):
    p=1
    while y:
        p=p*x
        y=y-1
    return p

x=3
y=5
print(f'{x}^{y}=',pow(x,y))

Write a Python program to read a list of numbers and sort the list in  decreasing order without using any built in functions. Separate function should be written to sort the list where in the name of the list is passed as the parameter.(University Question)

# Function to sort list in decreasing order
def sort_desc(numbers):
    n = len(numbers)
    for i in range(n):
        for j in range(i + 1, n):
            if numbers[i] < numbers[j]:  # Swap for decreasing order
                numbers[i], numbers[j] = numbers[j], numbers[i]

# Read list of numbers from user
num_list = []
count = int(input("Enter the number of elements: "))
for _ in range(count):
    num = int(input("Enter a number: "))
    num_list.append(num)

# Sort the list
sort_desc(num_list)

# Display the sorted list
print("Sorted list in decreasing order:", num_list)

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

1.Python Introduction