Site icon TestingDocs.com

User Defined Functions in Python

User Defined Functions in Python

Let’s write a Python program with a user-defined function to calculate a year’s total and average rainfall.

Python Program

#-----------------------------------------------
#Calculate total rainfall for the duration in months
#-----------------------------------------------
def total_rainfall(rainfall, durationInMonths):
    total = 0
    for i in range(durationInMonths):
        total +=rainfall[i] 
    return total


#-----------------------------------------------
#Calculate the average rainfall for a month
#-----------------------------------------------
def average_rainfall(rainfall, durationInMonths):
    return round(float(total_rainfall(rainfall, 
durationInMonths)/durationInMonths),3)

#-----------------------------------------------
# Main 
#-----------------------------------------------
def main():
    MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jly', 'Aug', 'Sep',
 'Oct', 'Nov', 'Dec']
    durationInMonths=12
    rainfall = []
    
    for i in range(durationInMonths):
        rainfall.append(float(input("Enter the rainfall for " + MONTHS[i] 
+ " in cm:= ")))

    print("Total Rainfall :=" + str(total_rainfall(rainfall,durationInMonths))
 + " cm")
    print("Average Rainfall :=" + str(average_rainfall(rainfall,durationInMonths))
 + "cm")
  

main()

Screenshot

 

Program Output

Enter the rainfall for Jan in cm:= 0
Enter the rainfall for Feb in cm:= 0
Enter the rainfall for Mar in cm:= 0
Enter the rainfall for Apr in cm:= 0
Enter the rainfall for May in cm:= 0
Enter the rainfall for Jun in cm:= 5.5
Enter the rainfall for Jly in cm:= 12.8
Enter the rainfall for Aug in cm:= 19.5
Enter the rainfall for Sep in cm:= 22.0
Enter the rainfall for Oct in cm:= 0
Enter the rainfall for Nov in cm:= 0
Enter the rainfall for Dec in cm:= 0
Total Rainfall :=59.8 cm
Average Rainfall :=4.983 cm

Exit mobile version