Python function arguments and parameters

python function arguments

Functions enable programmers to break down codes into simpler and more manageable chunks, and in this tutorial, you will learn about Python function arguments and parameters.

Functions are reusable blocks of codes, often written to solve a given task. A lot of times, functions are defined to accept data, upon which it processes to produce a specific outcome.

While defining functions, variables representing the kind of data to expect by the function are provided. These variables are known as parameters.


#function definition
def message(name):
    print(f'hello {name}')

#function call
message('Kate')

#output
hello Kate

In the above example, the function message is defined with only a single parameter – name. In the function call, a value – Kate is provided as an argument for the function.

Function arguments

Functions are not executable on their own, and to execute code contained in a function you have to call the function. If the function is defined with parameters, it means that you are required to provide matching values, also known as arguments.

Hence, parameters refer to the pieces of information that a function expects, while arguments are the values provided to the function.

There are different ways in which you can pass your argument to a function, and these form the basis of the following categorization of arguments.

  • positional arguments
  • keyword arguments
  • Default arguments
  • Arbitrary arguments

Positional arguments

For positional arguments, arguments are passed to functions in proper positional order. So, if you want to pass values as positional arguments, each argument must match the parameter in the function definition. In order not to get an error or unexpected results, then be careful not to mix up the order.


def numbers (a, b, c):
    result=a+b-c
    print(result)

#calling the function
numbers (5, 3, 1) #output 7

#calling the function not following the order
numbers (5, 1, 3) #output 3

Keyword arguments

Another way of passing values to functions is through keyword arguments. Here, values are assigned to variables with names, corresponding to those of the parameters in the function definition.

Thus, you don’t have to provide values to a function to match the position or order of the parameters.

However, you are required to pass a total number of arguments that amount to that of the parameters defined in the function, but the order is not important.


#keyword arguments
def greetings(name, title, message):
    greet=f'{message}{title}{name}!'
    print(greet)

#calling by keyword arguments
greetings(message = 'Good morning', title='Mr.', name= 'Kenneth')


#calling by positional arguments
greetings('Kenneth', 'Mr.', 'Good Morning')

Default arguments

Default arguments enable you to use default values where arguments are not supplied. The parameters are given default values during function definition, and if no argument is provided during the function call, the default values are used.

Keep in mind that parameters with a default value should be defined after those that do not have defaults, in order to be interpreted correctly.

 
def power (value, exponentiation = 2): 
    result = 1 
    if exponentiation is None: 
        result = value ** 2 
    else: 
        result = value ** exponentiation 
    print (result) 

#Calling the function 
power (2, 3) #output
power (2) #output

Arbitrary arguments

Arbitrary arguments or variable-length arguments make it possible to pass take a variable number of arguments to a function. This is particularly useful when you don’t know how many arguments to expect from a function. Hence, python offers a way to collect an arbitrary number of arguments. They are two types and they include:

  • Non-keyword arbitrary arguments
  • Keyword arbitrary arguments

Non-keyword arbitrary arguments

Non-keyword arbitrary arguments are also referred to as args. These arguments make it possible to collect an arbitrary number of positional arguments using the * asterisk parameter. This asterisk instructs the Python interpreter to pack the values it receives into a tuple.

# non-keyword arguments *args
def func(*args):
    for value in args:
        print(value)

#calling the function
func('yellow', 'blue', 'green', 'purple')
#outputs
#yellow
#blue
#green
#purple

In the above example, the asterisk parameter *args is used to pack the arguments passed into the function func into a tuple with the name args. The items contained in the tuple – args, are then looped and the respective values are printed.

In essence, the asterisk preceding the name args is a way of telling Python to pack values into a tuple.

Below is another example, but this time, the asterisk is used to pack the values into a tuple before being passed to the function – func.

 
# non-keyword arguments *args 
def func(*args): 
    for value in args: 
        print(value) 

#calling the function with a tuple 
countries = ('Spain', 'Brazil', 'Mexico') 
func(*countries) #outputs

Keyword arbitrary arguments

Keyword arbitrary arguments, also known as kwargs allow you to accept a variable number of arguments in the pairs of keywords and values using a double asterisk **. This double asterisk creates a dictionary that packs the key-value pairs of arguments into a dictionary.

# keyword arguments **kwargs
def func(**kwargs):
    #print the dictionary
    print(kwargs)
    for kwarg in kwargs.values():
        #print the values in the dictionary
        print(kwarg)

#calling the function with arbitrary keyword arguments
func(a='apple', b='mango', c='orange', d='pineapple', e='pawpaw')
#outputs
#{'a': 'apple', 'b': 'mango', 'c': 'orange', 'd': 'pineapple', 'e': 'pawpaw'}
#apple
#mango
#orange
#pineapple
#pawpaw

You can also use the double asterisk to break down a dictionary into key-value pairs before passing as an argument to a function as shown below:

 
dict = {'name':'Paul', 'age':25, 'gender':'male'} 
func(**dict) 
#outputs 
#{'name': 'Paul', 'age': 25, 'gender': 'male'}
#Paul
#25
#male

Passing arguments of different types

We have looked at different ways of passing arguments to functions. Now, let’s see how you can combine these various ways in the example below:

#mixed arguments
def greetings(name, title, message):
greet=f'{message}{title}{name}!'
print(greet)

#This is correct
greetings('Kenneth',title= 'Mr.', message='Good Morning')

#This is wrong
greetings('Kenneth', title= 'Mr.', 'Good Morning')

#This is also wrong
greetings(name='Kenneth', title= 'Mr.', 'Good Morning')

Keep in mind that if you must combine different types of arguments in a function call, the positional arguments come first, followed by keyword arguments, then non-keyword arbitrary arguments and lastly, the keyword arbitrary arguments.


Leave a Reply

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