Suppose you have a set of few lines of code which is used and executed at multiple places. Instead of writing it again and again at multiple places, these lines are written at a single point and grouped into a function. Where ever they are required, this function is called. Thus, a function is a group of lines of code which can be used to perform a task and called from different places.
Benefits of a function
- A function promotes reusability as multiple repetitive lines are written only once and can be used where required.
- It also promotes modularity as dividing the code into pieces converts it into smaller independent modules.
- It makes the code cleaner, organized and easier to understand since writing all the code at one place makes makes it very difficult to understand and modify.
- It makes maintenance easier. Think about it that when same logic is repeated at many places and there is a slight change in that logic, then that change needs to be done at all the places. While if that logic is grouped into a function, then that change only needs to be done at a single place.
- It makes testing of code easier since you do not need to test multiple repeating lines again and again if they are grouped into a single function.
Creating a function
A function is created using def keyword followed by the name of function and arguments of function enclosed between parenthesis. These arguments are optional and are required only if you want to pass some values to the function though parenthesis after function name are mandatory. If there are no arguments to the function, parenthesis will be empty.
def <function_name> (): # no-argument function # statement one # statement two # other statements def <function_name>(arg1, arg2...): # function with arguments # statement one # statement two # other statements
There can be any number of arguments supplied to a function. Statements of a function should be indented at the same level to denote that they belong to that function.
A function may or may not return a value. If a function needs to send a value back to the calling code, it is done by using return statement with value to be returned written after
return. Remember that when
return is encountered, function execution is stopped and the function returns immediately. Any code written after
return will not be executed.
Calling a function
A function is called by using its name followed by parenthesis. If the function expects any arguments, then those arguments should be provided between parenthesis separated by a comma. A function can be called only after it has been defined else you get an Unresolved reference error.
Below example defines a function which accepts two numbers as arguments and prints their sum.
# prints the sum of two numbers def sum(first_number, second_number): sum = first_number + second_number print("Sum of numbers is " + str(sum)) # calling function sum(2,3)
Remember that values of arguments when calling a function are passed in the same order in which they are given. In above example,
first_number will be 2 and
second_number will be 3.
Number of arguments which the function expects and which you pass while calling the function should match else you get an error. Example,
# prints the sum of two numbers def sum(first_number, second_number): sum = first_number + second_number print("Sum of numbers is " + str(sum)) # calling function sum(2) # only one argument
The function is expecting two arguments but we are calling it with a single argument. When this code is executed, you get an error TypeError: sum() missing 1 required positional argument: ‘second_number’
Returning values from function
A function becomes more useful if it performs some task and produces a result and it is also capable of returning that result back to the calling code. A function can return a value using the
return keyword followed by the value to return. Example,
def sum(first_number, second_number): sum = first_number + second_number return sum # calling function result = sum(2, 3) # assigning the return value to a variable print("Sum of numbers is " + str(result))Value returned from a function should be assigned to a variable in the calling code or the returned value can also be used directly. That is, below line is also valid.
print("Sum of numbers is " + str(sum(2, 3)))
return statement should be the last statement in the function body.
Default function arguments
As explained earlier, if a function is defined with arguments then an equal number of arguments need to be supplied while calling this function. However, python gives you a flexibility to this rule by the use of default arguments. By using default arguments, you can provide the value of an argument while defining it in the function.
If a function argument is provided a default value, then there is no need to supply its value at the time of calling the function. Example,
def defaultArg(a, b=5): print(b) defaultArg(2) # prints 5 defaultArg(2, 10) # prints 10, overrides default value
Look in the above code, a function accepting two arguments is defined out of which one argument has a default value. When this function is called with a single argument, then the default value of second argument is considered.
Note that while calling a function, if you supply a value for the argument which also has a default value, then the value supplied while calling the function overrides the default value.