User Defined Functions in Python
User Defined Functions in Python
A User Defined Function (UDF) in Python is a function that is created by the user (i.e., programmer) to perform a specific task. It allows code to be modular, reusable, and easier to manage.
📌 What is a Function?
A function is a block of organized, reusable code used to perform a single, related action.
✅ User Defined Function
In Python, you can create your own functions using the def keyword. Let’s write a Python program with a user-defined function to calculate a year’s total and average rainfall.
🔧 Syntax of a UDF
def function_name(parameters):
# function body
statements
return value
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