Function Argument and Parameter#

The argument is a value, a variable, or an object that we pass to a function or method call.

There can be two types of data passed in the function.

  • The First type of data is the data passed in the function call. This data is called arguments.

  • The second type of data is the data received in the function definition. This data is called parameters.

    • Arguments can be literals, variables and expressions.

    • Parameters must be variable to hold incoming values.

Alternatively, arguments can be called as actual parameters or actual arguments and parameters can be called as formal parameters or formal arguments.

Python Function Arguments#

In Python, you can define a function that takes variable number of arguments. In this article, you will learn to define such functions using default, keyword and arbitrary arguments.

In Python, there are 2 types of arguments allowed.

  1. Positional Arguments (Basic)

  2. Variable Function Arguments

Positional Arguments (Basic)#

In the User-defined function topic, we learned about defining a function and calling it. Otherwise, the function call will result in an error. For example:

# Example 1:

def greet(name, msg):
    """This function greets to the person with the provided message"""
    print("Hello", name + ', ' + msg)

greet("Arthur", "Good morning!")
Hello Arthur, Good morning!

Explanation:

Here, the function greet() has two parameters.

Since we have called this function with two arguments, it runs smoothly and we do not get any error.

If we call it with a different number of arguments, the interpreter will show an error message. Below is a call to this function with one and no arguments along with their respective error messages.

greet("Arthur")    # only one argument
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-98a1ccc168e9> in <module>
----> 1 greet("Arthur")    # only one argument

TypeError: greet() missing 1 required positional argument: 'msg'
greet()    # no arguments
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-76bf7a927991> in <module>
----> 1 greet()    # no arguments

TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'
# Example 2:

def add(a, b):
    print(a - b)

add(90, 30)  # Output 60
add(60, 30)  # Output -30
60
30
# Example 2: If you try to use pass more parameters you will get an error.

def add(a, b):
    print(a - b)
add(109, 633, 9)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5b50fb5d02c4> in <module>
      3 def add(a, b):
      4     print(a - b)
----> 5 add(109, 633, 9)

TypeError: add() takes 2 positional arguments but 3 were given

Note: In the Positional argument number and position of arguments must be matched. If we change the order, then the result may change. Also, If we change the number of arguments, then we will get an error.

# Example 3:

def evenodd(x):     # x is parameters or formal parameters or formal arguments.
    if (x % 2 == 0):
        print("even")
    else:
        print("odd")

# Driver code
evenodd(6)   # here 2 is argument or actual perameter
evenodd(9)   # here 3 is argument or actual perameter
even
odd
# Example 4:

def cube(x):
    "This x a passed num value into this function, return cube of x"
    y=x*x*x;
    return y

# Now you can call cube function
z=cube(2)  #required to pass argument
print(z)
8

Variable Function Arguments#

In Python, there are other ways to define a function that can take variable number of arguments.

Three different forms of this type are described below:

  1. Default Arguments

  2. Keyword Arguments

  3. Arbitrary/Variable-length Arguments

Python Default Arguments#

Default arguments are arguments that take the default value during the function call. If we do not pass any argument to the function, then the default argument will take place. We can assign default values using the = assignment operator. For example:

# Example 1:

def greet(name, msg="Good morning!"):  # two arguments: `name` is fixed arg and 'msg' is variable arg

    print("Hello", name + ', ' + msg)


greet("Alan")
greet("Bruce", "How do you do?")
greet("Carson","Good night!")
Hello Alan, Good morning!
Hello Bruce, How do you do?
Hello Carson, Good night!

Explanation:

In this function, the parameter name does not have a default value and is required (mandatory) during a call.

On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional during a call. If a value is provided, it will overwrite the default value.

Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.

This means to say, non-default arguments cannot follow default arguments. For example, if we had defined the function header above as:

>>> def greet(msg = "Good morning!", name):

We would get an error as:

SyntaxError: non-default argument follows default argument
# Example 2: function with default argument

def message(name="Everyone"):
    print("Hello", name)

# calling function with argument
message("David")

# calling function without argument
message()
Hello David
Hello Everyone

Explanation:

When we call a function with an argument, it will be considered that value.

Like in the above example, we passed name="David" we pass to the function, then the function will consider that value. If we do not pass any argument, it will be considered "name=Everyone" as a default value.

# Example 3: it prints default age if it is not passed

def emp_data(name, emp_id, age, company="Baidu.com"):  # total 4 arguments (3 is fixed and 1 is variable)
    print("Details of: ",name)
    print("Empoyee Id : ",emp_id)
    print("Age : ",age)
    print("Company : ",company)

#call emp_data fun
emp_data("Bill",101,21,"Samsung.com")
print("-----------------------")
emp_data("Cory",102,22)
Details of:  Bill
Empoyee Id :  101
Age :  21
Company :  Samsung.com
-----------------------
Details of:  Cory
Empoyee Id :  102
Age :  22
Company :  Baidu.com

Python Keyword Arguments#

Keyword arguments are related to the function calls. A keyword argument is an argument value, passed to function preceded by the variable name and an equals sign.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

# Example 1:

greet("Eric", "How do you do?")

# 2 keyword arguments
greet(name = "Eric",msg = "How do you do?")

# 2 keyword arguments (out of order)
greet(msg = "How do you do?",name = "Eric") 

# 1 positional, 1 keyword argument
greet("Eric", msg = "How do you do?")           
Hello Eric, How do you do?
Hello Eric, How do you do?
Hello Eric, How do you do?
Hello Eric, How do you do?

As we can see, we can mix positional arguments with keyword arguments during a function call. But we must keep in mind that keyword arguments must follow positional arguments.

Having a positional argument after keyword arguments will result in errors. For example, the function call as follows:

greet("Eric","How do you do?")
Hello Eric, How do you do?
greet(name="Eric","How do you do?")  # Will result in an error
  File "<ipython-input-13-0d17a834dca2>", line 1
    greet(name="Eric","How do you do?")  # Will result in an error
                      ^
SyntaxError: positional argument follows keyword argument
# Example 2:

def print_fullname(firstname, lastname):
    space = ' '
    full_name = firstname  + space + lastname
    return full_name
print(print_fullname(firstname = 'Milaan', lastname = 'Parmar'))
Milaan Parmar
# Example 3:

def add_two_numbers (num1, num2):
    total = num1 + num2
    return total
print(add_two_numbers(num2 = 3, num1 = 2)) # Order does not matter
5
# Example 4:

def calculate_age (current_year, birth_year):
    age = current_year - birth_year
    return age;
print('Age: ', calculate_age(2019, 1819))
Age:  200
# Example 5:

def remainder(dividend,divisor):
    x=dividend%divisor
    return x

#rem = remainder(10,3)
rem = remainder(divisor = 3, dividend = 10) # keyword argument
print("remainder of 10/3 : ",rem)
remainder of 10/3 :  1
# Example 6:

def message(name, surname):
    print("Hello", name, surname)

message(name="Frank", surname="Harper")
message(surname="Clayton", name="Gretta")
Hello Frank Harper
Hello Gretta Clayton

In keyword arguments, order of argument doesn’t not matter, but the number of arguments must match. Otherwise, we will get an error.

While using keyword and positional argument simultaneously, we need to pass 1st arguments as positional arguments and then keyword arguments. Otherwise, we will get SyntaxError. See the following example.

# Example 7:

def message(first_nm, last_nm):
    print("Hello..!", first_nm, last_nm)

# correct use
message("Frank", "Harper")
message("Frank", last_nm="Harper")

message(first_nm="Frank", "Harper")  # SyntaxError: positional argument follows keyword argument
  File "<ipython-input-19-b8ab82a1062c>", line 10
    message(first_nm="Frank", "Harper")  # SyntaxError: positional argument follows keyword argument
                              ^
SyntaxError: positional argument follows keyword argument

Python Arbitrary/Variable-length Arguments#

Sometimes, we do not know in advance the number of arguments that will be passed into a function. Python allows us to handle this kind of situation through function calls with an arbitrary number of arguments.

We can pass any number of arguments to this function. Internally all these values are represented in the form of a tuple.

In the function definition, we use an asterisk * before the parameter name to denote this kind of argument. For example:

# Example 1: 

def greet(*names):
    """This function greets all the person in the names tuple."""
    # names is a tuple with arguments
    for name in names:
        print("Hello", name)

greet("Gary", "Hank", "Ivan", "John")
Hello Gary
Hello Hank
Hello Ivan
Hello John

Here, we have called the function with multiple arguments. These arguments get wrapped up into a tuple before being passed into the function. Inside the function, we use a for loop to retrieve all the arguments back.

# Example 2: 

def addition(*numbers):
    total = 0
    for no in numbers:
        total = total + no
    print("Sum is:", total)

addition()                 # 0 arguments
addition(10, 5, 3, 6, 9)   # 5 arguments
addition(96, 77, 3.6)      # 3 arguments
Sum is: 0
Sum is: 33
Sum is: 176.6
# Example 3: 

def sum_all_nums(*nums):
    total = 0
    for num in nums:
        total += num     # same as total = total + num 
    return total
print(sum_all_nums(2, 3, 5)) # 10
10

Default and Arbitrary Number of Parameters in Functions

# Example 1: 

def printinfo( arg1, *vartuple ):
    "This prints a variable passed arguments"
    print ("Output is: ")
    print (arg1)
    for var in vartuple:
        print (var)
    return

    # Now you can call printinfo function
printinfo( 10 ) # We have given only one value for the argument
printinfo( 70, 40, 20 )
printinfo( 30, 60, 90, 120 )
Output is: 
10
Output is: 
70
40
20
Output is: 
30
60
90
120
# Example 2: 

def generate_groups (team,*args):
    print(team)
    for i in args:
        print(i)
print(generate_groups('Team-1','Milaan','Arthur','Clark','Ethan'))
Team-1
Milaan
Arthur
Clark
Ethan
None

Function as a Parameter of Another Function#

# Example 1: You can pass functions around as parameters

def square_number (n):
    return n * n
def do_something(f, x):
    return f(x)
print(do_something(square_number, 3)) # 27
9