Sometimes, while working we need to use a particular piece of code again and again by changing a few inputs or values. Due to this reason of reusability, we use functions in Python. A function is an organized block of code that can be reused whenever required. A function takes a few inputs, performs the specified computation, and gives us the desired output. We need to call the required function every time we wish to use it.
There are two kinds of functions in Python:
- Built-in functions
- User-defined functions
In case you have not tried earlier exercises and want to learn it from the start, we have the table below.
Built-in Functions are those which are already available to us by Python. For example, print (), type (), max(), min(), etc.
#Built in Functions print(' Hello') Hello #Output a = 24 print(type(a)) class 'int' #Output v = (10,20,30,40,50) print(max(v)) print(min(v)) 50 #Output 10 #Output
User-defined functions are those which we define in Python. Apart from the functions already available to us, Python gives us the option to define our own functions which cater our own specific needs.
Let’s see how we create our own function.
Creating a Function
We use the def keyword to define a function in Python.
Syntax to define a function:
def function_name(x): #block of code return expression
We write the desired function name after the def keyword in the code. The x inside the brackets represents the inputs we need to specify in our function. The block of a function starts after the colon (:) and all the lines within the block are identated. After the return keyword, we write the expression we require to get our desired output.
Let us see a few examples for the same.
Suppose we want to create a function which converts Temperature in degree Celsius to degree Fahrenheit, we can do it as follows:
#Function to convert Celsius to Fahrenheit def celsius_to_fahrenheit(cel): fah = (cel* 9/5) + 32 return print(fah) #Calling the function celsius_to_fahrenheit(0) #Inserting input value as 0 degree celsius 32.0 #Output
However, it is not necessary that we create functions in Python just to perform certain computations with numbers, they can be also created to perform operations on strings as well. For example, as follows:
#Function on String def name(x): print("Today is a wonderful day",x) #Calling the function name('John') Today is a wonderful day John #Output
We can also have more than one input in our function. Suppose we wish to add two numbers and want to create a function in python for it, we can do it follows:
#Function with many inputs #Function to add two numbers def sum_ab(a,b): c = a+b return print(c) #Calling the function sum_ab(5,4) 9 #Output
Therefore, along these lines, we can create as many functions as we want and fulfil our objective.
This article was written and published by Jinal Shah. Please do share your views or feedback.
Thank you for reading.