All the IPython Notebooks in Python Functions lecture series by Dr. Milaan Parmar are available @ GitHub
In this class, you will find the advantages of using user-defined functions and best practices to follow.
Functions that we define ourselves to do certain specific task are referred as user-defined functions. The way in which we define and call functions in Python are already discussed.
Functions that readily come with Python are called built-in functions. If we use functions written by others in the form of library, it can be termed as library functions.
All the other functions that we write on our own fall under user-defined functions. So, our user-defined function could be a library function to someone else.
# Example 1: illustrate the use of user-defined functions
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
def my_addition(num1,num2):
sum = float(num1) + float(num2)
return sum
#num1 = 9.3
#num2 = 6.9
print("The sum is", my_addition(num1, num2))
Enter first number: 9.3 Enter second number: 6.9 The sum is 16.200000000000003
Explanation:
Here, we have defined the function my_addition()
which adds two numbers and returns the result.
This is our user-defined function. We could have multiplied the two numbers inside our function (it's all up to us). But this operation would not be consistent with the name of the function. It would create ambiguity.
It is always a good idea to name functions according to the task they perform.
In the above example, print() is a built-in function in Python.