Python Function Argument

Python allows for the definition of functions that accept a variety of arguments. In this lesson, you will learn how to define such functions utilizing default, keyword, and arbitrary arguments.


What is an Argument?

An argument is a value given to a function in mathematics to acquire the function’s outcome. Another name for it is an independent variable. Also, the information given to a function can be referred to as both a parameter and an argument.

From the viewpoint of a function:

The variable in the function definition listed between parentheses is a parameter. When a function is called, a value is supplied as an argument. Let’s see an example to understand the argument concept.

Example

def myFirstFunction(arg):
print(arg + "Python Function")
myFirstFunction("My First ")

Output

My First Python Function

Here, there is one parameter for the myFirstFunction() function. The fact that we used an argument while calling this function ensures that everything goes smoothly and without errors.

A function must always be called with the appropriate parameters by default. In other words, if your function requires 2 arguments, you must call it with 2 arguments, not more or fewer. If we use a different number of arguments while calling it, the interpreter will provide an error message. Here are two calls to this function, one with two arguments and one without, along with the corresponding error messages.

Example 1

def myFirstFunction(arg):
print(arg + "Python Function")
myFirstFunction()

Output

Traceback (most recent call last):
File "", line 3, in 
TypeError: myFirstFunction() missing 1 required positional argument: 'arg'

Example 2

def myFirstFunction(arg):
print(arg + "Python Function")
myFirstFunction('My',' First')

Output

Traceback (most recent call last):
File "", line 3, in 
TypeError: myFirstFunction() takes 1 positional argument but 2 were given

Python Function Variable Arguments

Functions had a set amount of arguments up until this point. There are more ways to define a function in Python that can accept a variable number of arguments, and the next sections define this kind in three different ways.

  1. Python Default or Positional Arguments
  2. Python keywords or named Arguments
  3. Python Arbitrary Keyword Arguments

Python Default or Positional Arguments

In Python, function arguments may have default values. The assignment operator (=) allows us to give an argument a default value while defining a function. Here’s an illustration.

Example

def sumFunc(var1, var2=2):
print("Sum of ",var1," and", var2, "=", var1 + var2)
sumFunc(20000)
sumFunc(99999, 100000)

Output

Sum of 20000 and 2 = 20002
Sum of 99999 and 100000 = 199999

The parameter name in this function is required (mandatory) during a call and does not have a default value. If a value is entered, the python interpreter will replace it with the default value. On the other hand, the default value for the message option is 2. It is, therefore, optional while on a call.


Python keyword or named Arguments

We can also send parameters with the key = value syntax in the Python function. Thus, it doesn’t matter what order the arguments are presented.

Example

def sumFunc(var1, var2, var3):
print("Sum of ",var1,"+", var2,"+", var2, "=", var1 + var2 + var3)
sumFunc(var1=200,var2=400, var3=200)

Output

Sum of 200 + 400 + 400 = 800

When we call a function with some arguments, the arguments’ values is assigned based on where they are on the call stack. For instance, when calling the function sumFunc() as sumFunc(var1=200,var2=400, var3=200), var1, var2 and var3 is assigned 200,400 and 300 in def sumFunc(var1, var2, var3) respectively and will print 800.

Python Arbitrary Keyword Arguments

If unsure how many keyword arguments you’ll give your function, place two asterisks before the parameter name in the function specification.

You may not always know the number of arguments given into a function in advance. Python enables function calls with any amount of arguments, which we may use to handle this circumstance. We utilize an asterisk (*) before the parameter name in the functional specification to indicate this type of argument. Here’s an illustration.

Example 1

def sumFunc(*numbers):
for num in numbers:
print(num)
sumFunc( "One","Two","Three","Four")

Output

One
Two
Three
Four

Example 2

def sumFunc(**data):
for key, value in data.items():
print(f"{key}: {value}")
sumFunc(num1= "One",num2="Two",num3="Three",num4="Four")

Output

num1: One
num2: Two
num3: Three
num4: Four

In this case, we invoked the function with many arguments. Before being supplied to the function, these arguments are condensed into a tuple. We employ a for loop inside the function to get all the arguments back.

You might have noticed two examples with one * and two **. Let’s understand the difference between them below in detail.


Difference between *args and **kwargs in Python

Python *args and **kwargs, their uses, and functions with examples are covered in this article.

In computer programming, we define a function to provide reusable code for a particular task. To carry out that operation, we call a function with a specific value, known in Python, as a function argument.

We believe reading Python Function, and Python Function Arguments would be best.

Let’s say we create a function to add two numbers.

Example

def sumFunc(i,j):
print(i+j)
sumFunc(1,2)

Output

3

The sumFunc () function with two arguments, I and j, is present in the previous program. The total of the two numbers is returned when the sumFunc() method is used with two arguments.

Let’s see what occurs when the sumFunc() function is called with more than two arguments.

def sumFunc(i,j):
print(i+j)
sumFunc(1,2,3)

Output

Traceback (most recent call last):
File "", line 3, in 
TypeError: sumFunc() takes 2 positional arguments but 3 were given

When unsure of how many arguments to send to a function, we utilize *args and **kwargs as arguments. We can use special symbols in Python to pass a function with various parameters.

Pair of unique symbols are:

  • *args Non-Keyword Arguments
  • **kwargs (Keyword Arguments)

Python *args Non-Keyword Arguments

We are unsure of the maximum amount of arguments that can be supplied to a function, just as in the example above. Python’s *args feature enables us to pass a function a configurable number of non-keyword arguments.

We must use the asterisk * before the parameter name to pass arguments of varying lengths to the function.

The parameters are given as a tuple; inside the function with the same name as the parameter (but without the asterisk *), they form a tuple.

Example

def sumFunc(*numbers):
res=0
for num in numbers:
res = res + num
print("Result:",res)
sumFunc( 1,2,3)
sumFunc( 1,2,3,4)
sumFunc( 1,2,3,4,5)

Output

Result: 6
Result: 10
Result: 15

The sumFunc() function can accept argument lists of any length because we utilized the option *numbers in the example above. We supplied the function with three separate tuples of varying lengths. A loop that adds the passed input and prints the outcome is present inside the method.


Python **kwargs Keyword Arguments

Python uses *args to pass variable-length non-keyword arguments to functions; However, you cannot use *args to pass keyword arguments. Python offers a solution for this issue called **kwargs, which enables us to pass the function variable-length keyword arguments.

We use the double asterisk ** before the parameter name to indicate this argument in the function. The arguments are supplied as a dictionary. Inside the function, they create a dictionary with the same name as the parameter but without the double asterisk **

Example

def StudentInfo(**data):
print(type(data))
for key, value in data.items():
print("{} is {}".format(key,value))
StudentInfo(Name="Humna", Age=22, Class="2nd Semester", Grade="A+")
StudentInfo(Name="John", Age=23, Class="2nd Semester", Grade="B+")

Output


Name is Humna
Age is 22
Class is 2nd Semester
Grade is A+

Name is John
Age is 23
Class is 2nd Semester
Grade is B+

A StudentInfo() function in the program above takes a parameter named **data. The StudentInfo() function received two dictionaries with varying argument lengths. Inside the StudentInfo() function, there is a ‘for loop’ that processes the data from the given dictionary and prints its value.


Things to Remember:

  • The special keywords *args and **kwargs allow functions to accept arguments of varying lengths.
  • *Args passes a variable number of non-keyworded arguments, depending on which operation the tuple can perform.
  • To a function that may do dictionary operations, **kwargs passes a configurable number of keyword arguments.
  • The function is adaptable thanks to *args and **kwargs.