Skip to content

All about Function arguments in Python

Function arguments in Python

In this tutorial we will learn about function arguments in Python . We can pass the following type of argument during function calling –

  • Required Argument in Python
  • Default Argument in Python
  • Keyword Argument in Python
  • Variable-length Argument in Python

Now we will learn about all this argument with examples . Before going further through this tutorial it is recommended to read about Python functions .

Required Argument in Python

In this case, we need to pass same number of argument at same order during function calling as we have passed as parameter during defining a function . It means that if we pass two parameters during defining a function as (number , string) then we have to pass two parameters as (number , string) during function calling otherwise it will raise an TypeError .

When we define a function, the data we use in the parentheses (()) in the function header is called parameter. And when we call a function, the data we use in parentheses (()) is called argument.

Example 1: Change the position of required argument

#defining a function
def mul (string, number):
    print(string + str(number))
    
#passing required argument 
mul("python", 3)
mul(3, "python") #this line will show error
python3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_13840/3851980042.py in <module>
      5 #passing required argument during function calling
      6 mul("python", 3)
----> 7 mul(3, "python") #this line will show error

C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_13840/3851980042.py in mul(string, number)
      1 #defining a function
      2 def mul (string, number):
----> 3     print(string + str(number))
      4 
      5 #passing required argument during function calling

TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • In the above code, first a function mul has been defined which takes two parameters as (string, number) .
  • Then the mul() function is called where two arguments (string, number) are passed, which prints python-3 in the output.
  • After that again the mul() function has been called where the argument has been passed without following any rules, so the program has shown error.

Example 2: Change the no of required argument

#defining a function
def mul (string, number):
    print(string + str(number))

# calling mul function with 1 argument
mul("python")  # this line will raise error
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_10912/3477392913.py in <module>
      1 # calling mul function with 1 argument
----> 2 mul("python")  # this line will raise error

TypeError: mul() missing 1 required positional argument: 'number'

As mul() function requires two argument but we have given one argument so the program has raised an error .

Default Argument in Python

Default argument in Python is that argument which is not required . It is an argument which has a default value . During definition of a function when we use a parameter with a default value then during function calling if we don’t pass that argument then program will not show any error . This argument is the default argument . During function calling if we don’t pass default argument then it will take the default value but if we pass default argument with new value then it will take the new value .

Example 1:

list_of_present_student = []
list_of_absent_student = []

#defining a function
def attendance (name, atten = "absent"):
    if (atten == "present"):
        list_of_present_student.append(name)
    elif (atten == "absent"):
        list_of_absent_student.append(name)
        
#calling function attendance
attendance("rajkumar", "present")
attendance("sourav", "present")
attendance("sudipta")

print(list_of_present_student)
print(list_of_absent_student)
['rajkumar', 'sourav']
['sudipta']
  • In the above code we have first made two empty lists, one for the present student and the other for the absent student.
  • Then we wrote a function attendance, if atten == "present" then the name of the student will be added to the list of present student and if atten == "absent" then the name of the student will be added to the list of absent student. Here we have used atten as default parameter, whose default value is "absent". This means that if we do not pass the atten during function calling, it will take the default value.
  • Then we called the function total three times . In the first two times we took value of atten argument as "present", so the two names "rajkumar" and "sourav" have been added to the list of present students. But last time we didn’t use atten argument so it took the default value "absent" and added the name "sudipta" to the list of absent student.

Keyword argument in Python

In this case we will use arguments as key-value pair where key will be name of the argument and value will be the value of that argument . In this case we don’t need to maintain the order of the arguments but the key-value pair must be correct.

Example 1:

#defining a function
def address (name, place):
    print(name, "is living in", place)
    
# calling the function with keyword argument    
address(place = "kolkata", name = "rahul")
address(name = "arup", place = "bihar")
address(name = "bangalore" , place = "sudipta")
rahul is living in kolkata
arup is living in bihar
bangalore is living in sudipta
  • In the above code a function address is written which takes two parameters that is name and place.
  • When we have called the function for the first time we have changed the order of parameters . But in the second time we have kept the order intact . We can see that in both the case program has given correct output .
  • But in the third case we have changed the key-value pair . Here we have used value of place as value of name and value of name as value of place . So the program has given wrong output . So we need to remember that for keyword argument order does not matter but key-pair value does .

Variable-length argument in Python

Sometimes we do not know how many arguments will be used in a function and sometimes in the same program a function may need to be run with three or four or various no of arguments, in that case we use variable-length argument. . It is of two types –

Arbitrary arguments(*args) in Python

When we don’t know how many arguments will be passed in a function, we use * before the parameter name when defining the function.

Example 1: Add multiple numbers in Python

#defining a function with arbitrary argument
def add (*numbers):
    print(numbers)
    print(type(numbers))
    
    mysum = 0
    for number in numbers:
        mysum += number
    print("sum =",mysum)    
        
add(1, 2) 
add(4, 5, 6, 7, 8)
(1, 2)
<class 'tuple'>
sum = 3
(4, 5, 6, 7, 8)
<class 'tuple'>
sum = 30
  • In the above code we have defined a function called add where we have used * before the name of the parameter. Now we can give any number of arguments while calling add() function.
  • The add() function is first called with the argument 1,2 which has become a tuple (1,2) under the effect of * . We can also check whether it is tuple through type function. Then we iterate each number of the tuple with the help of for-loop and find their sum. We can also find the sum of all number in the tuple directly through the built-in sum() function. Later add() function is called again with 4,5,6,7,8 argument.

Example 2: using required argument with *args

If we want to use another required argument with *args in a function, then that argument must be used before *args.

# defining the add function
def add(number, *numbers):
    print("number =",number)
    print("sum of numbers =",sum(numbers))
    
add(4) 
add(4, 2, 6)
number = 4
sum of numbers = 0
number = 4
sum of numbers = 8
  • In the above code a function named add is written which takes one required argument number and another arbitrary argument *numbers as parameter.
  • The first time the add() function is called with argument as 4, it takes number as 4 which prints 4 in the output . Since there is no other argument, numbers becomes () (empty tuple) which returns 0( sum of empty tuple ) in the output.
  • The second time the add() function is called with argument as 4,2,6 , it takes number as 4 which prints 4 in the output, Since there are other arguments 2,6 so numbers becomes (2,6) which prints 8( sum of (2,6) ) in the output .

Example 3: using *args with required argument

def add(*numbers, number):
    print(number)
    print(sum(numbers))
     
add(4, 2, 6)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_14036/1422992790.py in <module>
      3     print(sum(numbers))
      4 
----> 5 add(4, 2, 6)

TypeError: add() missing 1 required keyword-only argument: 'number'
  • In the above code, the parameters of the aforesaid add function have been changed by changing the place of *args and required argument.
  • So when the add() function is called with 4,2,6 argument then numbers became (4,2,6), so no argument was found for the number. Since there is no argument present so program couldn’t assign any value with number parameter during function calling. Since number is a required argument so the program has shown error. No matter with how many arguments the function is called, all the arguments will be assigned to the numbers as tuples and there will be no argument left for the number, so if we put the required argument after * args, the program will always show error.

Arbitrary keywords argument(**kwargs) in Python

When we do not know how many keyword arguments will be passed in a function, we use ** before the parameter name when defining the function.

Example 1:

#defining a function
def address (**names):
    print(names)
    print(type(names))
    print(names["name"], "is living in", names["place"])
    
address(place = "kolkata", name = "rahul") 
address(name = "sudipta", place = "puri", state = "Orissa")
{'place': 'kolkata', 'name': 'rahul'}
<class 'dict'>
rahul is living in kolkata
{'name': 'sudipta', 'place': 'puri', 'state': 'Orissa'}
<class 'dict'>
sudipta is living in puri
  • In the above code we have defined a function called address where we have used ** before the name of the parameter. Now when calling the address function we can give any number of keyword arguments.
  • First, the address() function is called with the argument place = "kolkata", name = "rahul" which is changed to {"place": "kolkata", "name": "rahul"} i.e. turned into a dictionary under the effect of ** . We can also check whether it is a dictionary through type() function. Then a statement is printed by accessing the value with the key of the dictionary.

Note 1:

To use a required argument or keyword argument with **kwargs in the same function, first we should use the required argument or keyword argument and then **kwargs.

Note 2:

If we need to use required argument , *arg and **kwargs in the same function we should use required argument first then *args and finally **kwargs .

Example 1: Using required argument , *args and **kwargs
def printdetails (name, *args, **kwargs):
    print(name)
    print(args)
    print(kwargs)
    
printdetails("sourav", 5, 6, 7, python = 3, java = 8) 
sourav
(5, 6, 7)
{'python': 3, 'java': 8}

In the above code, first required argument, then * args, then ** kwargs are used as parameters in the printdetails() function. So the program did not show any error.

Example 2: Using required argument , **kwargs and *args
def printdetails(name, **kwargs, *args):
    print(name)
    print(args)
    print(kwargs)
    
printdetails("sourav", python = 3, java = 8, 5, 6, 7)
  File "C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_14036/4005345609.py", line 1
    def printdetails(name, **kwargs, *args):
                                     ^
SyntaxError: invalid syntax

In the above code, first required argument, then **kwargs, then *args are used as parameters in the printdetails() function. As we can’t use **kwargs before *args , So the program has raised SyntaxError.

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply