Parameters of a function in Python

This post is lesson 15 of 54 in the subject Python Programming Language

In this article, we will learn about the parameters of functions in Python. When calling a function, we need to pass arguments to it. To distinguish between parameters and arguments and to have a good foundation for learning this topic, you can read the article Concept of Parameters and Arguments in C++.

1. Defining functions with parameters

When a function is defined, the parameters are also determined inside the function’s parentheses. A function can have any number of parameters. Each parameter is separated by a comma (,).

def hello(name, msg):
    """Say hello to a person with message"""
    print("Hello ", name, ", ", msg, sep='')

hello("John", "Welcome to Gochocit.com!")

Result

Hello John, Welcome to Gochocit.com!

The function hello(name, msg) has 2 parameters. When calling the function, if we only pass in 1 argument or don’t pass in any arguments, it will result in an error.

def hello(name, msg):
    """Say hello to a person with message"""
    print("Hello ", name, ", ", msg, sep='')

#TypeError: hello() missing 1 required positional argument: 'msg'
hello("John")
#TypeError: hello() missing 2 required positional arguments: 'name' and 'msg'
hello()

2. Default arguments in Python functions

When defining a function, we can provide default values for parameters by using the assignment operator ‘=’. We call them default arguments. For example:

def hello(name, msg="Welcome to Gochocit.com!"):
    """Say hello to a person with message"""
    """If the msg is not provided, it defaults to "Welcome to Gochocit.com!"
    """
    print("Hello ", name, ", ", msg, sep='')

#Not provided any value for default argument
hello("John")
#Provided a value for default argument
hello("John", "How are you?")

Result

Hello John, Welcome to Gochocit.com!
Hello John, How are you?

In the example above, the parameter name requires an argument when calling the function because it does not have a default value. Meanwhile, the parameter msg has a default value of “Welcome to Gochocit.com!”, so it can be passed as an argument or left out.

Note: All parameters of a function can have default values. When some parameters have default values and others do not, it is important to remember that all parameters with default values must be placed to the right of the parameters without default values. Failing to follow this rule will result in an error.

Example:

#SyntaxError: non-default argument follows default argument
def hello(msg="Welcome to Gochocit.com!", name):
    """Say hello to a person with message"""
    """If the msg is not provided, it defaults to "Welcome to Gochocit.com!"
    """
    print("Hello ", name, ", ", msg, sep='')

When the parameter msg is given a default value and is placed before (on the left of) the parameter name which has no default value, a SyntaxError will occur.

3. Calling a function using parameter names

When calling a function, the values passed correspond to the parameters in order from left to right. However, there is a way to call a function by specifying parameter names along with their respective values. This is called a keyword argument, which is useful when the order of the parameters is not remembered.

Example:

def hello(name, msg):
    """Say hello to a person with message"""
    print("Hello ", name, ", ", msg, sep='')

# 2 keyword arguments
hello(name = "John", msg = "How are you?")
# 2 keyword arguments (out of order)
hello(msg = "How are you?", name = "John") 
#1 positional, 1 keyword argument
hello("John", msg = "How are you?")

Result

Hello John, How are you?
Hello John, How are you?
Hello John, How are you?

We can use both parameter name and parameter position when calling a function. However, using the parameter name must always come after the parameter position. For example:

def hello(name, msg):
    """Say hello to a person with message"""
    print("Hello ", name, ", ", msg, sep='')

#SyntaxError: positional argument follows keyword argument
hello(name = "John", "How are you?")

When calling a function and using the parameter name before the parameter order, it will cause a SyntaxError.

4. Calling a function with arbitrary arguments in Python

In some cases, we do not know the number of arguments passed to a function when calling it. Python allows passing different numbers of arguments for each function call by using the asterisk (*). There are 2 ways to use the asterisk (*) in this case:

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

Using *args (Non-Keyword Arguments)

Use one asterisk * before the parameter name to use Non-Keyword Arguments. The parameter name follows the rule of naming identifiers.

def hello(*names):
    """Say hello to all person in names"""
    for name in names:
        print("Hello", name)

hello("John", "James", "Mary", "Robert", "Jennifer")

Result

Hello John
Hello James
Hello Mary 
Hello Robert
Hello Jennifer

The operating principle of Non-Keyword Arguments is that the arguments are passed in a tuple. We use for to iterate through each element in this tuple.

Using **kwargs (Keyword Arguments)

Use double asterisks ** before the parameter name to use Keyword Arguments. The arguments passed to the function all have an associated identifier name.

def hello(**notices):
    """Send notices to all person"""
    for key, value in notices.items():
        print("%s, %s" % (key, value))

hello(John="How are you?", James="Welcome to Gochocit.com!", Mary="Nice to meet you!")

Result

John, How are you?
James, Welcome to Gochocit.com!
Mary, Nice to meet you!

5. Are function arguments in Python passed by value or by reference?

If you have read the articles on Variables and Variable Memory in Python, you already know that in Python, all variables are passed by reference to an object. When we call a function, we pass a variable to it, and at this point, a new reference to the object of that variable is created. For instance, suppose we have a function and we call it as follows:

def myFunction(val):
    if(val>0):
        print("val =", val, "is greater than 0")
    val = 9.1
    print("val =", val)
x = 5
myFunction(x)
print("x = ", x)

Result

val = 5 is greater than 0
val = 9.1
x =  5

In the example above, the parameter passing mechanism for the function myFunction(val) occurs as follows:

  1. When assigning x = 5, x refers to an object of the int class that stores the value 5.
  2. We call the function myFunction(x) with the variable x as the argument passed to the function.
  3. Then, a variable val is created. This val variable will also refer to the object of the int class that stores the value 5 that x refers to. That is, both x and val variables refer to the same object 5.
  4. But then, when val = 9.1 is assigned, val will refer to an object of the float class that stores the value 9.1. That means val no longer refers to object 5. Only x still refers to object 5.
  5. After the function ends, the val variable and object 9.1 are also deleted. And the x variable still refers to object 5 without being changed when exiting the function.
The variables x and val refer to the same object 5
The variables x and val refer to the same object 5
The variables x and val do not refer to the same object 5
The variables x and val do not refer to the same object 5

Example of passing a list as an argument to a function in Python

#x is a new reference to same list lst
def myFunction(x):
    x[0] = 99
    x[2] = 999
 
lst = [10, 11, 12, 13, 14, 15]
myFunction(lst)
print(lst)

Result

[99, 11, 999, 13, 14, 15]

In the above example, lst and x both refer to the same object that stores a list. When x changes the elements in this object, the access through lst will also result in the same changes.

But if x is assigned to another list, then x and lst will refer to different objects. For example:

def myFunction(x):
    # A new object is assigned to x.
    x = [20, 30, 40]

lst = [10, 11, 12, 13, 14, 15]
myFunction(lst)
print(lst)

Result

[10, 11, 12, 13, 14, 15]

When assigning x = [20, 30, 40], x now refers to a different list object. Therefore, x and lst are no longer related to each other.

Example of passing an integer argument to a function in Python

def myFunction(val):
    # A new object is assigned to x.
    val = 20
    print("val = ", val)

x = 10
myFunction(x)
print("x = ", x)

Result

val =  20
x =  10

When val=20 is assigned, val now refers to a different int object. Therefore, x and val are no longer related to each other.

To summarize, when passing arguments to a function in Python, the method used pass by reference. However, it is important to note that in Python, when a value is assigned to a variable using the assignment operator =, the old reference link is broken. This is an essential point to consider when passing arguments to a function in Python.

5/5 - (1 vote)
Previous and next lesson in subject<< How to Define a Function in Python?Distinguishing global, local, and nonlocal variables in Python >>

Leave a Reply

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