Function Parameters in Python

PythonBeginner
Practice Now

Introduction

In this lab, we will explore how to define and use functions with parameters in Python. Functions become much more powerful when they can accept input, which makes them dynamic and reusable.

We will cover several types of function parameters, including positional parameters, default values, keyword arguments, and variable-length arguments. Through practical examples, you will learn how to create flexible functions that can handle a variety of inputs.

Define Functions with Positional Parameters

Parameters allow us to pass data into a function, making its behavior adaptable based on the input it receives. Let's start with the most common type: positional parameters. The arguments passed to a function are assigned to these parameters based on their order.

First, locate the file positional_params.py in the file explorer on the left side of the WebIDE and open it.

Now, let's define a function named hello that accepts one parameter, name. Add the following code to the positional_params.py file:

def hello(name):
    print(f'Hello, {name}!')

hello('John')
hello('Alice')

In this code, name is a parameter, which acts as a placeholder in the function definition. When we call the function, like hello('John'), the value 'John' is an argument that gets assigned to the name parameter.

To run the script, open a new terminal in the WebIDE by clicking Terminal -> New Terminal in the top menu. Then, execute the following command:

python3 ~/project/positional_params.py

You will see the following output, showing that the function produced different results for different arguments:

Hello, John!
Hello, Alice!

If a function is defined with positional parameters, you must provide a corresponding argument for each one when you call it. Forgetting to do so will result in an error.

Use Default Parameter Values

It is often useful to provide a default value for a parameter. If an argument for that parameter is not provided during the function call, the default value is used. This makes the parameter optional.

Let's see what happens when we call a function without a required argument. Open the default_params.py file and add the following code:

def hello(name):
    print(f'Hello, {name}!')

hello()

Save the file and run it from the terminal:

python3 ~/project/default_params.py

This will produce a TypeError because the function hello was expecting one argument but received none.

Traceback (most recent call last):
  File "/home/labex/project/default_params.py", line 4, in <module>
    hello()
TypeError: hello() missing 1 required positional argument: 'name'

To fix this, we can assign a default value to the name parameter. Modify the default_params.py file by replacing its content with the following code:

def hello(name="World"):
    print(f'Hello, {name}!')

hello()
hello("Jobs")

Now, run the script again:

python3 ~/project/default_params.py

The output will be:

Hello, World!
Hello, Jobs!

The first call uses the default value "World", while the second call uses the provided argument "Jobs".

Important Rule: In a function definition, all parameters without default values must come before any parameters with default values. For example, def func(a, b="default") is correct, but def func(a="default", b) will cause a SyntaxError.

Pass Arguments Using Keywords

When calling a function, you can explicitly name the parameters you are providing arguments for. These are called keyword arguments. Their main advantage is that order does not matter, which can make your code more readable.

Open the keyword_args.py file and add the following code:

def person(name, age):
    print(f"{name} is {age} years old.")

## Calling with keyword arguments - order does not matter
person(name="Zhang San", age=25)
person(age=50, name="Li Si")

Save the file and run it from the terminal:

python3 ~/project/keyword_args.py

You will see that both calls work correctly, regardless of the argument order:

Zhang San is 25 years old.
Li Si is 50 years old.

You can also mix positional and keyword arguments in a single function call. However, you must follow one rule: all positional arguments must come before any keyword arguments.

Now, replace the content of keyword_args.py with the following to see this rule in action:

def person(name, age):
    print(f"{name} is {age} years old.")

## This is a valid mix of positional and keyword arguments
person("Wang Wu", age=26)

## This would cause a SyntaxError: positional argument follows keyword argument
## person(age=28, "Zhao Liu")

Run the script again. The valid call will execute as expected.

python3 ~/project/keyword_args.py

Expected output:

Wang Wu is 26 years old.

Handle a Variable Number of Arguments

Python functions can be designed to accept a variable number of arguments. This is useful when you do not know in advance how many arguments will be passed to your function.

Variable Positional Arguments (*args)

By placing an asterisk * before a parameter name, you can collect an arbitrary number of positional arguments into a tuple. The name args is a convention, but you can use any valid parameter name.

Variable Keyword Arguments (**kwargs)

By placing a double asterisk ** before a parameter name, you can collect an arbitrary number of keyword arguments into a dictionary. The name kwargs is also a convention.

Let's combine these concepts. Open the variable_args.py file and add the following code:

## Using *args to sum a variable number of numbers
def calculate_sum(*numbers):
    print(f"Arguments received as a tuple: {numbers}")
    total = sum(numbers)
    print(f"Sum: {total}\n")

## Using **kwargs to capture extra profile information
def person_profile(name, age, **other_info):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"Other Info: {other_info}\n")

## Calling the functions
calculate_sum(1, 2, 3)
calculate_sum(10, 20, 30, 40, 50)

person_profile('Wang Wu', 26, gender="Male", job="Writer")
person_profile('Zhao Liu', 28, city="Beijing", status="Active")

Run the script from the terminal:

python3 ~/project/variable_args.py

The output shows that numbers is a tuple and other_info is a dictionary:

Arguments received as a tuple: (1, 2, 3)
Sum: 6

Arguments received as a tuple: (10, 20, 30, 40, 50)
Sum: 150

Name: Wang Wu
Age: 26
Other Info: {'gender': 'Male', 'job': 'Writer'}

Name: Zhao Liu
Age: 28
Other Info: {'city': 'Beijing', 'status': 'Active'}

Explore Special Parameter Types

Python allows you to enforce how arguments can be passed to a function, making your function's signature clearer and less ambiguous. You can specify parameters as positional-only or keyword-only.

Positional-Only Parameters (/)

To specify that parameters can only be passed by position, place them before a forward slash (/) in the function definition.

Keyword-Only Parameters (*)

To specify that parameters can only be passed by keyword, place them after an asterisk (*). If the * is not followed by a parameter name, it means all subsequent parameters must be keyword-only.

Let's see how to combine these types. Open the special_params.py file and add the following code. This example defines a function with positional-only, standard, and keyword-only parameters.

def school_info(name, /, standard_param, *, city):
    print(f'Positional-Only (name): {name}')
    print(f'Standard (standard_param): {standard_param}')
    print(f'Keyword-Only (city): {city}')
    print('---')

## In this function:
## - `name` must be passed by position.
## - `standard_param` can be passed by position or keyword.
## - `city` must be passed by keyword.

## Valid calls
school_info("Peking University", "PKU", city="Beijing")
school_info("Tsinghua University", standard_param="THU", city="Beijing")

## Invalid call examples (commented out to prevent errors)
## school_info(name="Zhejiang University", "ZJU", city="Hangzhou")  ## TypeError: name is positional-only
## school_info("Fudan University", "FDU", "Shanghai")               ## TypeError: city is keyword-only

Run the script to see the result of the valid calls:

python3 ~/project/special_params.py

The output will be:

Positional-Only (name): Peking University
Standard (standard_param): PKU
Keyword-Only (city): Beijing
---
Positional-Only (name): Tsinghua University
Standard (standard_param): THU
Keyword-Only (city): Beijing
---

This syntax helps create robust and self-documenting functions, reducing ambiguity in how they should be called.

Summary

In this lab, you have learned the fundamentals of using parameters in Python functions. We covered how to define and call functions with positional parameters, how to make parameters optional by providing default values, and how to use keyword arguments for more readable code. You also explored how to create flexible functions that can accept a variable number of positional (*args) and keyword (**kwargs) arguments. Finally, we looked at special syntax (/ and *) to enforce how arguments must be passed, which improves the clarity and robustness of your functions.