Function in Python

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.

# syntax to create a function with parameters
print("syntax to create a function with parameters")
def function_name(parameters):
	"""docstring of function_name function"""
	statement(s)
	return value
  • 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

# definition of a function with parameters and docstring
def shbytes(course):
	"""This is the docstring of a function shbytes function takes courses as argument"""
	print(course)    # Print the value of parameters passed

# docstring of the function
print("docstring of the function")
print(shbytes.__doc__) # Access docstring of the function
shbytes("Python")      # Call to the function with argument
  • 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 with Python argument passed as the parameter value.

Program Output

docstring of the function
This is the docstring of a function shbytes function takes courses as argument # docstring of the function
Python # Print parameter value

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

# function definition with 3 parameters
def shbytes_3(c1, c2, c3):
	print(c1)
	print(c2)
	print(c3)

# Scenario 1 - call to the function with 3 arguments
print("call to the function with 3 arguments")
shbytes_3("AWS","Python","ML") # function called with 3 arguments

# Scenario 2 - function with 3 parameters, but called with 2 arguments
print("function with 3 parameters, but called with 2 arguments")
try:
	shbytes_3("AWS","Python") # function called with 2 arguments
except TypeError as err:             # raised TypeError - missing argument
	print("error", err)

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 the TypeError.

Program Output

call to the function with 3 arguments
AWS
Python
ML      # All three parameter values are printed

function with 3 parameters, but called with 2 arguments
error shbytes_3() missing 1 required positional argument: 'c3'  # Raised TypeError

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.

# function definition with 3 parameters, last parameter has default value
def shbytes_3(c1, c2, c3="ML"):
	print(c1)
	print(c2)
	print(c3)

# function called with 2 arguments
shbytes_3("AWS","Python") # function called with 2 arguments

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

AWS    # Print first argument assigned value
Python # Print second argument assigned value
ML     # Print default value for last parameter

Function parameter with dynamic datatype arguments

In Python, function parameters can also be any collection object like list, tuple, set, dictionary, array or string.

# function definition with dynamic datatype parameter and iteration inside function
def shbytes_list(courses):
	for course in courses:  # iterate over the sequence collection
		print(course)       # Print each element

shbytes_list("Python") # function called with string argument
shbytes_list(["AWS","Python","ML","DevOps"]) # function called with list argument
shbytes_list(("AWS","Python","ML","DevOps")) # function called with tuple argument
shbytes_list({"AWS","Python","ML","DevOps"}) # function called with set argument
shbytes_list({1:"AWS",2:"Python",3:"ML",4:"DevOps"}) # function called with dictionary argument

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.

# function with 2 parameters
def shbytes_course(course, description):
	print("course => ", course)
	print("description => ", description)

# function call with keyword arguments
shbytes_course(description="Python Programming - Beginner to Master", course="Python")

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

course =>  Python
description =>  Python Programming - Beginner to Master

Function arbitrary arguments

Arbitrary Arguments (*args) are used when we want a function to accept a variable number of arguments.

# arbitrary arguments - *args parameters of a function
print("arbitrary arguments - *args parameters of a function")
def star_args(*courses):    # function parameter with astrisk
	print(len(courses))
	print(courses)
	
star_args("AWS","Python","ML")  # function called with 3 arguments
star_args("AWS","Python")       # function called with 2 arguments
star_args("AWS","Python","ML","Power BI") # function called with 4 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

arbitrary arguments - *args parameters of a function
3       # function called with 3 argument
('AWS', 'Python', 'ML')
2       # function called with 2 arguments
('AWS', 'Python')
4       # function called with 4 arguments
('AWS', 'Python', 'ML', 'Power BI')

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).

# arbitrary keyword arguments - **args parameters of a function
print("arbitrary keyword arguments - **args parameters of a function")
def keyword_args(**courses):  # parameter with double astrisk accepts key-value pair elements
	print(len(courses))
	print(courses)

# Scenario 1 - arbitrary keyword arguments - **args - no error when all arguments in key=value pair
print("arbitrary keyword arguments - **args - no error when all arguments in key=value pair")
keyword_args(c1="AWS",c2="Python",c3="ML")  # function called with 3 key-value pair arguments
keyword_args(c1="AWS",c2="Python")          # function called with 2 key-value pair arguments
keyword_args(c1="AWS",c2="Python",c3="ML",c4="Power BI")  # function called with 4 key-value pair arguments

# Scenario 2 - arbitrary keyword arguments - **args - error when argument not assigned in key=value pair
print("arbitrary keyword arguments - **args - error when argument not assigned in key=value pair")
try:
	keyword_args("AWS",c2="Python",c3="ML") # function called when arguments not assigned in key=value pair
except TypeError as err:  # Raise TypeError
	print("error", err)

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

arbitrary keyword arguments - **args - no error when all arguments in key=value pair
3      # function called with 3 key-value pair arguments
{'c1': 'AWS', 'c2': 'Python', 'c3': 'ML'}
2      # function called with 2 key-value pair arguments
{'c1': 'AWS', 'c2': 'Python'}
4      # function called with 4 key-value pair arguments
{'c1': 'AWS', 'c2': 'Python', 'c3': 'ML', 'c4': 'Power BI'}

arbitrary keyword arguments - **args - error when argument not assigned in key=value pair
error keyword_args() takes 0 positional arguments but 1 was given  # Raise TypeError

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.
g_variable = 100       # global variable

# Scenario 1 - local variable with same name as global variable
print("local variable with same name as global variable")
def l_scope_function():
    l_variable = 10    # local variable
    print(l_variable)
    g_variable = 90    # without global keyword will create local variable
    print(g_variable)  # print value of local variable

l_scope_function()

# Scenario 2 - access global variable with global keyword
print("access global variable with global keyword")
def g_scope_function():
    l_variable = 10    # local variable
    print(l_variable)
    global g_variable  # access global variable with global keyword
    print(g_variable)  # print value of global variable

g_scope_function()

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(). Accessing g_variable = 90 in this function, without global 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(). Accessing global g_variable in this function, with global keyword will access the variable defined outside the function. Changing the value of this variable will change the value of global variable.

Program Output

local variable with same name as global variable
10   # l_variable value from l_scope_function
90   # g_variable (local variable) value from l_scope_function

access global variable with global keyword
10   # l_variable value from g_scope_function
100  # g_variable (global variable) value from g_scope_function

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.

# Scenario 1 - function return value using return keyword
print("function return value using return keyword")
def multiple_numbers(number1, number2):  # function with 2 parameters
	return number1 * number2             # return multiple of two numbers

multiple = multiple_numbers(3, 5)
print("multiple", multiple)

# Scenario 2 - function return multiple values
print("function return multiple values")
def numbers_operation(number1, number2):          # function with 2 parameters
	return number1 + number2, number1 - number2   # return sum and subtract of two numbers

sum, subtract = numbers_operation(5, 3) # return multiple values and assigned to variables
print("sum", sum, "subtract", subtract)

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

function return value using return keyword
multiple 15       # value returned from function

function return multiple values
sum 8 subtract 2  # multiple values returned from function

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

# lambda function - with multiple parameters
print("lambda function - with multiple parameters")

product = lambda num1, num2, num3: num1 * num2 * num3 # product is the lambda function

# calling of lambda function
print("calling of lambda function")
print("Product of values 3, 4, 5 is - : ", product(3, 4, 5))
print("Product of values 10, 20, 30 is - : ", product(10, 20, 30))

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

lambda function - with multiple parameters

calling of lambda function
Product of values 3, 4, 5 is - :  60       # return value of product(3, 4, 5)
Product of values 10, 20, 30 is - :  6000  # return value of product(10, 20, 30)

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() (from functools) => Applies a function cumulatively to the items in a list, reducing it to a single value.
numbers_list = [14, 19, 31, 44]

# Use lambda function with map() 
squared = list(map(lambda x: x ** 2, numbers_list))
print(squared)  # Output => [196, 361, 961, 1936]

# Use lambda function with filter() 
even_numbers = list(filter(lambda x: x % 2 == 0, numbers_list))
print(even_numbers)  # Output => [14, 44]

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.

# function recursion - calling of same function from its own function definition
print("function recursion - calling of same function from its own function definition")
def sum_sequence(number):
	if(number <= 0):
		return number
	else:
		return number + sum_sequence(number - 1)

print("function to calculate sum of sequence like 5 + 4 + 3 + 2 + 1")
print(sum_sequence(5))

print("function to calculate sum of sequence like 6 + 5 + 4 + 3 + 2 + 1")
print(sum_sequence(6))

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

function recursion - calling of same function from its own function definition
function to calculate sum of sequence like 5 + 4 + 3 + 2 + 1
15
function to calculate sum of sequence like 6 + 5 + 4 + 3 + 2 + 1
21

Summary

In this article, we learned about functions in Python. Following topics were discussed:

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.

Python Topics


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *