Function arguments#


Arguments are input parameters (e.g., numbers, strings, lists, tuples, etc) of the function. There are three types of arguments: none, required and/or optimal arguments.


# Function without argument
def print_usa():
    print('United States of America')
United States of America

This function has no arguments, and it will always do the simple printing. Let’s see a function with one argument

# Function with one argument
def celsius_to_fahrenheit(celsius):
    fahrenheit = (celsius * 9/5) + 32
    return fahrenheit

This above function has one argument, and it returns an error if you use it without input parameters (i.e., in this case, celsius temperature)

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_30380\ in <module>
----> 1 print(celsius_to_fahrenheit())

TypeError: celsius_to_fahrenheit() missing 1 required positional argument: 'celsius'

Keyword Arguments#

Let’s see a function with two required arguments:

# Define a function to print my name
def display_info(first_name, last_name):
    print('First Name:', first_name)
    print('Last Name:', last_name)

display_info('Vitor', 'Martins')


I intentionally preserved the position of my arguments and passed my first_name in the first argument and last_name in the second argument. This is known as positional arguments. Unlike positional arguments, we can use “keyword arguments” and pass the values with their respective arguments, providing my arguments in any order.

display_info(last_name = 'Martins', first_name = 'Vitor')

Above strategy is useful to build a function with required arguments and default arguments with pre-defined values.

For example:

# Define a new student with default arguments
def add_new_student(first_name, last_name, university='Mississippi State University', student_year='freshman'):
    print('First Name:', first_name)
    print('Last Name:', last_name)
    print('University:', university)
    print('Student year:', student_year)

# this works well (1)
add_new_student('Great', 'Student', university='Mississippi State University', student_year='freshman')
# this works well (2) because there are default values for the other two arguments
add_new_student('Great', 'Student')
# this works well (3) because it modifies one of the arguments
add_new_student('Great', 'Student', student_year='junior')
# this fails well (4) because it's missing one argument


It’s important to note that when using keyword arguments, all the positional arguments must come before the keyword arguments. For example, in the function call add_new_student(‘Great’, ‘Student’, university=’Mississippi State University’, student_year=’freshman’), “Great” is a positional argument, while student_year=’freshman’ is a keyword argument.

Another example:

def add_numbers( a = 7,  b = 8):
    sum = a + b
    print('Sum:', sum)

# function call with two arguments
add_numbers(2, 3)

#  function call with one argument
add_numbers(a = 2)

# function call with no arguments

Function With Arbitrary Arguments#

In few cases, we are not sure how many arguments will be passed into a function, and the arbitrary arguments provide the flexibility to pass a varying number of values during a function call. The asterisk (*) before the parameter name will denote the arbitrary argument, and the function will accept an arbitrary number of positional arguments, and they will be organized into a tuple within the function.

def sum_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

result = sum_numbers(1, 2, 3, 4, 5)
print(result)  # Output: 15

result = sum_numbers(10, 20)
print(result)  # Output: 30

Another option for arbitrary arguments is the arbitrary keyword arguments using **kwargs. The **kwargs parameter is more structured and uses the keyword arguments to build a dictionary within the function (i.e., keys are the argument names and the values are the corresponding argument values).

def display_info(**kwargs):
    for key, value in kwargs.items():
        print(key + ": " + str(value))

display_info(first_name="Vitor", last_name="Martins", university="Mississippi State University", role='faculty')

Lastly, *args and **kwargs can be used together in the function, so you will have both positional and keyword arguments arbitrarily.

def random_function(*args, **kwargs):
    for arg in args:
    for key, value in kwargs.items():
        print(key, value)

random_function(1, 2, 3, name='Vitor', role='faculty', university='MSU')