Function in Python

Master Python Function and Argument Types | Lambda expression – 10 mins read

Python function is very important from programmers prespective. Declaration and calling of python function is quite easy. def keyword is used to start function definition .It is followed by function name an parameters within small braces.For small function that contain only one expression, lambda expression can be used in place of standard function. Lambda expression are tricky ones but saves a lot of time if you master them. Let's get started with "Function in Python and types of function arguments".

Table of Contents

96 / 100

Introduction

Welcome to today’s session on “Python functions and various types of parameter”. In this Python tutorial, you’ll learn about function declaration and calling the function with various types of arguments.

You’ll also learn how and when to use a specific type of argument with the help of examples. In the end, you will learn about Anonymous function and scope of variables.

Let’s begin our tutorial with an introduction to the Python function ,followed by an introduction on how to declare and call a function.

If you aren’t following along, I would recommend you to go back where you left or start from here.

What is a Python Function ?

A python function is a block of reusable code that may takes some inputs as arguments, do some stuff with them and may provide some output.

Flow Chart of Python Function
Flow Chart of Python Function

Why use python function ?

1.Reusability – A python function written once can be called by user many times which saves both space and time.Like,if you want to calculate the GCD of two numbers you don’t write the whole logic instead use a builtin function.

2.ModularityIt is same as Divide and Conquer technique .A big program is divided into small modules. These small modules are function that takes some input,process them and gives output..The modules are short codes and easy to debug.
3.AbstractionA python function works like a black box . Once defined, all you need to remind is what goes inside i.e. parameters , what happens to them and what is the after result.
You don’t have to worry about the logic behind . It creates an invisible layer over the working of program.

.

Types of function

Like in C or C++, python language has some builtin function and it also supports creation of new function i.e. user-defined function.

Built in Python Function
Credit :- Python Official Docs 3.8.5

Defining A Function in Python

You can easily defined a python function by following these steps:-

  • The keyword def starts a python function definition . It is followed by function name and list of parameters within small parenthesis and a colon ‘:’.
  • The statements in the function body must be indented.
  • Ideally, the first statement of the function body is a function’s documentation string or docstring.

    A docstring is a string literal that gives short intro of function i.e. what is function all about and what it return as output.

  • The remaining statements and logic write inside the indented code block
  • At last , a return statement that indicates the end of the python function. A return statement with no value to return is same as returning None.
Structure of Python Function
Structure of Python Function

Syntax

def function_name(parameters):
“Function Documentation String”

……………….

Function Body

……………….

return expression or value

Example

>>> def digitsum(number):
...     "Return the sum of all digits in the number"
...     ans = 0
...     while(number>0):
...         ans+=number % 10
...         number //= 10
...     return ans
...
>>> print(digitsum)
<function digitsum at 0x00000205B9DAACA0>
After defining function, the interpreter associates a function object with the function name . Other variables can be made reference to function object .
>>> sumofdigit = digitsum
>>> print(sumofdigit)
<function digitsum at 0x00000205B9DAACA0>

Calling A Python Function

The function definition finalized the function name , parameters ,return type and the statement to execute in the function body.

You can execute it by calling it in the program with the arguments.Let us see an example to make things more clear.

>>> def digitsum(number):
...     "Return the sum of all digits in the number"
...     ans = 0
...     while(number>0):
...         ans+=number % 10
...         number //= 10
...     return ans
...
# Directly calling the  function in the program using 456 as an argument
>>> number = 456
>>> result = digitsum(number)
>>> print(result)
15                               # 4 + 5 + 6 = 15
# Using a reference t call the function.
>>> sumofdigits = digitsum
>>> print(sumofdigits(123))
6

Python Function Arguments

Arguments are the values that user sends in place of parameters when function is called. In C or C++ , the arguments can be passed by ‘Call by Value’ or ‘ Call by Reference’ .

Let us see what is the python mechanism for passing functional arguments.

Call by Object Reference

In python , arguments are passed by ‘Call by Object Reference’ i.e instead of value , the reference to the datatype object is passed.

The catch here is :-

  • If you pass immutable objects like integers , strings, tuples etc . , it is considered as ‘Pass By value‘. The change takes place inside the function body doesn’t affect the variable in the calling function.For example :-
# The value of n doesn't change outside the function
>>> def increment_by_two(n):
...     n+=2
...     print('Value of n in the function = ',n)
...     return
...
>>> n = 5
>>> print('Value of n before the fucntion is called = ',n)
Value of n before the fucntion is called =  5
>>> increment_by_two(n)
Value of n in the function =  7
>>> print('Value of n after the function is called = ',n)
Value of n after the function is called =  5
  • If you pass mutable objects like list, dictionary etc . , it is considered as ‘Pass By reference‘. The change takes place inside the function body affect the variable in the calling function.For example :-
# The value of l1 changes outside the function
>>> def append_list(l1,n):
...     l1.append(n)
...     print('Value of list in the function = ',l1)
...     return
...
>>> l1 = [1,2,3,4]
>>> n = 5
>>> print('Value of list before the fucntion is called = ',l1)
Value of list before the fucntion is called =  [1,2,3,4]
>>> append_list(l1,n)
Value of list in the function = [1,2,3,4,5]
>>> print('Value of list after the function is called = ',l1)
Value of list after the function is called =  [1,2,3,4,5]

Required Arguments

These types pf arguments are passed in the same order the parameters were. The number of arguments should match the number of parameters else the missing positional argument error raised.

For example: –

>>> def append_list(l1,n):
...     l1.append(n)
...     print('Value of list in the function = ',l1)
...     return
...
>>> l1 = [1,2,3,4]
>>> n = 5
>>> append_list(l1)                     # error will be raised
Traceback (most recent call last):
File "", line 1, in 
TypeError: append_list() missing 1 required positional argument: 'n'
>>> append_list(l1,n)
Value of list in the function  = [1,2,3,4,5]

Keyword Arguments

Keyword Arguments are preceded by identifier (parameter) in function call such as (age = argument) .The interpreter matches the argument list with parameter list using keyword so order of arguments is not considered.

For example:- The order of parameter is name -> address but the arguments are passed as address -> name.

>>> def bio(name,address):
...     print(name,'resides at',address)
...
>>> bio(address = 'www.topictrick.com',name = 'TOPICTRICK')
TOPICTRICK resides at www.topictrick.com

The catch here is :-

  • If you have both positional and keyword arguments in the function call , the positional arguments should precede the keyword arguments else error will be raised.

For example: –

>>> def bio(name,address):
...     print(name,'resides at',address)
...
>>> bio(address = 'www.topictrick.com','TOPICTRICK')
File "", line 1
SyntaxError: positional argument follows keyword argument
>>> def bio(name,address):
...     print(name,'resides at',address)
...
>>> bio('TOPICTRICK',address = 'www.topictrick.com')
TOPICTRICK resides at www.topictrick.com

Default Arguments

We can pass default value for one or more parameter .When the actual argument is passed it overrides the default value else the default value is used.

The default arguments are used exhaustively to reduce the chance of getting error if we missed some arguments.

For example :-

>>> def add(a,b,c = 0,d = 0):
...      return a+b+c+d
...
# With two values
>>> print(add(3,4))
7
# With three values
>>> print(add(2,3,5))
10
#With four values
>>> print(add(1,2,3,4))
10

We can apply the concept of function overloading default arguments.The same function can be called with different argument list.

The catch here is:-

  • When subsequent calls are made for a function, the default argument is checked once.This will create a problem if the default value is a mutable object.
>>> def add_pair(tup,dict1 = {}):
...      dict1[tup[0]] = tup[1]
...      return dict1
...
>>> print(add_pair((1,'one'))
{1:'one'}
>>> print(add_pair((2,'two'))
{1:'one',2:'two'}
>>> print(add_pair((3,'three'))
{1:'one',2:'two',3:'three'}

In above example, Ideally the output should be a dictionary of length 1 for every function call but the key – value pairs are adding up. So you should consider this situation while writing the code.


Variable Length Arguments(*args,**kwargs)

The developer at the time of function declaration may not know the exact number of positional or keyword arguments. In this scenario, the variable length arguments are passed.

*args – An arbitrary length of positional arguments can be passed, the interpreter converts all the arguments into a python tuple.

**kwargs – An arbitrary length of keyword arguments can be passed , the interpreter converts all the keywords arguments into a python dictionary.

args and kwargs are naming convention. You can also use other variable name. * and ** are necessary to represent a parameter of variable length.

Example#1 – Write a program to add elements of the list of arbitrary length.

>>> def add(*args):
...     ans = 0
...     for num in args:
...          ans+=num
...     return ans
...
>>> print(add(1,2,3,4,5,6,7))
28
>>> print(add(2,3,4))
9
In above example, positional arguments are mapped to args as tuple.

Example#2 – Write a program to print bio data of a person.

>>> def bio(**kwargs):
...     for key,val in kwargs.items():
...         print(key,'-->',val)
...     return
>>> bio(Name = 'Sherlock Holmes',Address = '221 Baker Street',Profession = 'Private Detective')
Name --> Sherlock Holmes
Address --> 221 Baker Street
Profession --> Private Detective

In the above example, all the keyword arguments are mapped to kwargs as python dictionary.


Python Trick : Special Arguments(Python 3.8 or more)

Special Arguments in Python Function
  • Positional-or-Keyword Arguments :- If ‘*’ or ‘/’ is not present in the function definition, the arguments can be passed as Positional or Keyword.
    Example – In the below example, we have passed name as positional and name as keyword arguments.
>>> def bio(name,address):
...     print(name,'resides at',address)
...
>>> bio('TOPICTRICK',address = 'www.topictrick.com')
TOPICTRICK resides at www.topictrick.com
  • Positional-Only Arguments :- All the parameter before ‘/’ are passed as position only. You cannot pass them as keyword argument and order of arguments also matters
    Example – In the below example, we have passed address as keyword argument which raises an error.
>>> def bio(name,address,/):
...     print(name,'resides at',address)
...
>>> bio('TOPICTRICK',address = 'www.topictrick.com')
Traceback (most recent call last):
File "", line 1, in 
TypeError: bio() got some positional-only arguments passed as keyword arguments: 'address'
>>> bio('TOPICTRICK',address = 'www.topictrick.com')
TOPICTRICK resides at www.topictrick.com
 
  • Keyword-Only Arguments :- All the parameter after ‘*’ are passed as keyword only. You cannot pass them as positional argument.
    Example – In the below example, we have passed name as positional argument which raises an error.
>>> def bio(*,name,address):
...     print(name,'resides at',address)
...
>>> bio('TOPICTRICK',address = 'www.topictrick.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bio() takes 0 positional arguments but 1 positional argument (and 1 keyword-only argument) were given
>>> bio(name = 'TOPICTRICK',address = 'www.topictrick.com')
TOPICTRICK resides at www.topictrick.com

Anonymous Function (lambda expression)

These are small anonymous function i.e. they are not declared as standard Python function. lambda keyword is used to declare these type of function.

  • An anonymous function can take multiple arguments but return only one value in form of expression.
  • They cannot contain multiple lines in body.
  • These are just function object .Hence, cannot be printed out using print statement directly.

These are used where function objects are passed and the function body contains a one-line code.

Example#1 : – In sort method, the key parameter takes a function object which applies on every element of sequence. The list is sorted according to the key.In our example ,we have a list of tuples and we want to sort the list acc. to second element of tuple.

lambda x: x[1] creates a functional object which takes tuple as an argument and select its second element as the key.

>>> l1 = [(1,2),(5,3),(8,-1),(2,11)]
>> l1.sort(key = lambda x:x[1])
>>> print(l1)
[(8, -1), (1, 2), (5, 3), (2, 11)]

Example#2 – Create a function which takes two integer as argument and return their sum

>>> add = lambda x,y : x+y
>>> print(add(1,2))
3

Return Statement

A return statement indicates the end of the function. It returns an expression to the caller. A function with no value to return is same as returning None.

return statement is optional

Example#1 :- Write a python function that returns the square of an number.

>>> def square(x):
...      return x*x
...
>>> print(square(3))
9

Example#2 :- Write a function that add element in a list.

>>> def append_item(l1,x):
...      l1.append(x)
...
>>> l1 = [1,2,3]
>>> x = 4
>>> print(append_item(l1,x))
None

In the above example, None is printed as output because the append_item function doesn’t return anything so default value is returned.