Function in Python
A function in Python is a reusable block of code designed to perform a specific task or operation. Functions allow us to organize our code into modules. It helps us makes code more readable, maintainable, and scalable. Function can take arguments, known as parameters to pass data and can return value as a result.
Why use functions
- Code Re-usability – Functions allows us to write code once and can use multiple times.
- Code Organization – Functions helps us to break complex problems into smaller, manageable tasks.
- Abstraction – Using function, we can focus on the task rather than the implementation details.
Syntax of a Function in Python
Functions in Python are defined using the def
keyword, followed by the function name, parameters (optional), and a colon (:
). The function body is indented under the function definition.
def
is a keyword in Python used to define a function.function_name
is the name given to the function. Python follows naming conventions for function names, variables and other elements. Function name in Python is in lowercase and uses underscores to separate the words.parameters
are the variables listed inside the parentheses in function definition. These parameters are optional.- arguments are the value sent to the function when it is called. These values are assigned to the function parameters.
- docstring is the document for the function. This is also optional. docstring can only be the first line of the function.
return
is used to send the result back to where the function was called. return is also optional.
Function Example
def shbytes(course):
=> This defines the function with one parameter. Docstring is defined for this function. This functions print the value of the parameter and does not return any object.shbytes.__doc__
=> Using__doc__
on the function name, we can access the docstring of the function.shbytes("Python")
We are making a call to the function withPython
argument passed as the parameter value.
Program Output
Function Parameters and Arguments
Types of parameters and arguments:
- Default Parameters can define default values for function parameters. If no argument is provided, the default value for that parameter is used.
- Positional Arguments – The arguments passed to the function are matched in the order (from left to right) in which they are defined.
- Keyword Arguments – When calling a function, we can specify the value to a parameter based on their names, so the order of parameters and passed arguments doesn’t matter.
- Arbitrary Arguments (
*args
) are used when we want a function to accept a variable number of arguments. - Arbitrary Keyword Arguments (
**kwargs
) allows a function to accept an arbitrary number of keyword arguments (passed as a dictionary).
Function parameters and positional arguments
def shbytes_3(c1, c2, c3):
=> We have defined a function with three parameters and will print the values of these three parameters
- In first scenario, we are calling function
shbytes_3("AWS","Python","ML")
with three arguments. Each argument value will be assigned to parameters at their respective positions (from left to right). This is taken as positional arguments. - In second scenario, we are calling function
shbytes_3("AWS","Python")
with two arguments. Argument values will be assigned to parameters at their respective positions (from left to right). Last parameter will not be assigned any value. Because of this mismatch between function parameters and arguments will raise theTypeError
.
Program Output
Function parameters with default value
To handle the scenarios where number of parameters are more than the number of arguments passed while calling the function, we can define the function with default value to parameters.
def shbytes_3(c1, c2, c3="ML"):
=> We have defined a function with 3 parameters. Last parameter c3
is given default value. Now, if we will call this function with 3 arguments then all 3 parameters will be assigned given values but if we call the function with only 2 arguments, then last parameter will take default value and will not raise TypeError. We are calling function shbytes_3("AWS","Python")
with 2 arguments.
Program Output
Function parameter with dynamic datatype arguments
In Python, function parameters can also be any collection object like list, tuple, set, dictionary, array or string.
def shbytes_list(courses):
– We have defined a function with 1 parameter and we are iterating over this parameter to print each element.
Since Python is a dynamically typed language, this parameter can be of any sequential datatype like string, list, tuple, set, dictionary or array. We called this function with different datatype object and iterated through its elements.
Function Keyword and Arbitrary Arguments
Function keyword arguments
Keyword Arguments – When calling a function, we can specify the value to a parameter based on their names, so the order of parameters and passed arguments doesn’t matter.
When we define a function with parameters, each parameter is given a name (keyword). While calling the function, we can assign the value to these parameters using their names (keywords). This is different than assigning the argument values based on the parameters respective positions.
def shbytes_course(course, description):
=> We have defined a function with 2 parameters. While calling this function we can assign them values based on their names (keywords). This way we can assign parameter values in any order. Like we are calling this function with shbytes_course(description="Python Programming - Beginner to Master", course="Python")
where first argument is assigned to description
parameter and second argument is assigned to course
parameter.
Program Output
Function arbitrary arguments
Arbitrary Arguments (*args
) are used when we want a function to accept a variable number of arguments.
Astrisk (*) is used to pack number of elements in sequential collection datatype like list and to unpack sequential datatype elements into individual variables. Read article to learn more about Packing and Unpacking of list in Python.
def star_args(*courses):
=> This defined function has parameter with astrisk (*). This allows us to provide arbitrary number of arguments to this function. We called this function with star_args("AWS","Python","ML")
=> 3 number of arguments, star_args("AWS","Python")
=> 2 number of arguments and star_args("AWS","Python","ML","Power BI")
=> 4 number of arguments.
Program Output
Function arbitrary keyword arguments
Arbitrary Keyword Arguments (**kwargs
) allows a function to accept an arbitrary number of keyword arguments as key-value pair (passed as a dictionary).
def keyword_args(**courses):
=> Function defined has parameter with double astrisk, which can accept arbitrary number of key-value pair arguments.
In first scenario, we called this function with keyword_args(c1="AWS",c2="Python",c3="ML")
=> 3 key-value pair arguments, keyword_args(c1="AWS",c2="Python")
=> 2 key-value pair arguments, keyword_args(c1="AWS",c2="Python",c3="ML",c4="Power BI")
=> 4 key-value pair arguments
In second scenario, we called this function with keyword_args("AWS",c2="Python",c3="ML")
, where all arguments are not key-value pair. This non key-value pair argument will be considered as positional argument, which does not match with any parameter. This will raise TypeError
.
Program Output
Function – Scope of Variables
Read article to learn about various scope in Python – Variable Scopes in Python
Variables defined inside a function are local to that function. They are not accessible outside of it, whereas global variables are accessible from anywhere in the script.
- Local Scope – Variables created inside a function can only be used inside that function.
- Global Scope – Variables created outside a function are global and can be accessed by any function.
- Modifying Global Variables in Functions – To modify a global variable inside a function, we need to access that variable using the
global
keyword.
In this program, we have defined a variable g_variable
outside of any function. We can access this variable inside any function using the global
keyword. Without the global
keyword, a new local variable with same name will be created.
- In scenario 1, we have defined a function
l_scope_function()
. Accessingg_variable = 90
in this function, withoutglobal
keyword will create a new local variable and can have different value than variable (with same name) outside the function. - In scenario 1, we have defined a function
g_scope_function()
. Accessingglobal g_variable
in this function, withglobal
keyword will access the variable defined outside the function. Changing the value of this variable will change the value of global variable.
Program Output
Function – Return Statement
Functions can return values using the return
keyword, which allows the function to output a result to be used later in the program. In Python, a function can return multiple values as well.
In scenario 1, we have defined a function multiple_numbers(number1, number2)
, which takes two parameters and return the multiplication of parameter values. At time of function call, we can get this returned value in a variable like multiple = multiple_numbers(3, 5)
.
In scenario 2, we have defined a function numbers_operation(number1, number2)
, which takes two parameters and return sum and subtraction of parameter values. Multiple value can be returned at the same time. At time of function call, we can get these returned values in variables like sum, subtract = numbers_operation(5, 3)
.
Program Output
Lambda function
In Python, Lambda functions are anonymous, one-liner functions that are used for short, simple operations. They are defined using the lambda
keyword.
Syntax => lambda arguments: expression
In this program, we have defined a lambda function using product = lambda num1, num2, num3: num1 * num2 * num3
. product
is the name of the lambda function, which takes 3 parameters and returns the product of the parameter values. We are calling lambda function product
using product(3, 4, 5)
and product(10, 20, 30)
.
Program Output
Use lambda function with high-order functions
Lambda functions are often used with higher-order functions like map()
, filter()
, and reduce()
.
map()
=> Applies a function to all items in an iterable.filter()
=> Filters elements in an iterable based on a condition.reduce()
(fromfunctools
) => Applies a function cumulatively to the items in a list, reducing it to a single value.
Function Recursion
Recursion occurs when a function calls itself in order to solve a problem. It’s useful for tasks like traversing trees or solving mathematical problems like factorials.
In this program, we have defined a function sum_sequence(number)
to calculate the sum of sequence for the given number. In this functions definition, we are calling the same function again like sum_sequence(number - 1)
, to get next number and add it to previous number.
Program Output
Summary
In this article, we learned about functions in Python. Following topics were discussed:
- Function in Python
- Function Parameters and Arguments
- Function Keyword and Arbitrary Arguments
- Function – Scope of Variables
- Function – Return Statement
- Lambda function
- Function Recursion
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.