A function is a block of code that can be written once and used as many times as one wants. Once defined, a function can be used by calling it wherever and whenever required.
What is the need for functions?
Imagine you need to write a chunk of code to get 10 latest blog posts from your database. Later, you also
need to write a code to get 10 latest blog categories. The code for both the requirements
would be quite similar. Instead of writing the similar code twice, you can define a function that
could handle both the requirements. This is the major use of functions. Despite this, there can be some other advantages of using functions.
- It helps to organize large code into smaller groups, making it easier to read and debug.
- It decreases the complexity of the code and gives us a well defined structure.
- As mentioned above, a function helps to reduce code duplication.
- Functions improve the clarity of code.
Once defined, a function can be used by calling it.
Creating a function
In Python, a function can be defined (or created) by using the ‘def’ keyword.
For example:
def printMessage():
print("Hello World")
This function will do nothing if we don’t call it.
def printMessage():
print("Hello World")
printMessage() #Function Call
Output: Hello World
Note: We can name a function anything except a predefined keyword. For example ‘bottle’ can be the name of a function but not print, as print is a predefined keyword in Python.
Functions with arguments
We can pass information to a function. This information is called arguments. We can pass any number of arguments in a function, separated by commas.
The function given below accepts two arguments.
def displayName(first_name, last_name):
print("My name is " + first_name + " " + last_name)
displayName("Vasu", "Rupolia")
displayName("John", "Doe")
Output:
My name is Vasu Rupolia
My name is John Doe
Default Arguments
We can pass default arguments in Python functions. Consider this function
def greet(name, message = 'Hello'):
print(message + " " + name)
greet("Vasu", "Hi")
Output:
Hi Vasu
In the above function, we have passed a default argument named message, and the default value is ‘Hello’.
If we pass the value of a default argument, it replaces the default value. As in our example ‘Hi’ replaced ‘Hello’. But we do not give value for a default argument, it takes the default value.
def greet(name, message = 'Hello'):
print(message + " " + name)
greet("Vasu")
Output:
Hello Vasu
If you don’t give default arguments, you must pass the exact number of arguments in the function call.
For example the below given function will generate an error.
def greet(name, message):
print(message + " " + name)
greet("Vasu")
Output: Error
Passing a list as an argument
We can also pass a Python list as an argument
def printCountries(country_list):
for x in country_list:
print(x)
printCountries(["India", "Japan", "USA"])
Output:
India
Japan
USA
Returning values
A function can also return a value rather than just printing something. To return something, we can use the ‘return’ keyword.
def addNumbers(num1, num2):
num3 = num1 + num2
return num3
addNumbers(2, 5)
This function will give no output, as we haven’t printed anything, but returned the sum of two numbers. We can collect this returned value in a variable and then use the value as we wish.
def addNumbers(num1, num2):
num3 = num1 + num2
return num3
result = addNumbers(2, 5)
print(f"The result is {result}")
Output: The result is 7
Types of functions in python
- Built-in functions
- User defined function
Inbuilt or Built in functions: Python has various built in functions like print, sum, len, type etc.
User defined functions: These are functions defined by a user. For example, the function named ‘greet’ defined above is a user defined function.
Lambda function: We will learn about this one in the next section.