Parameters

What are parameters in Python?

In Python, a function may require some values to perform its task. These values, known as parameters or arguments, are specified when we declare or define a function. Parameters are placeholders that get their values from outside the function when it is called.

Refer to the example function below:

1def greet(name):
2    print(f"Hello, {name}!")

In this example, name acts as a parameter for the greet function. The function takes one parameter and prints a greeting for that name.

How to use parameters

You can provide values to the function parameters during the function call. These values are known as arguments. The order in which you pass these values matters significantly as the values get assigned to the parameters according to their position.

Consider the example function declared earlier. You can call it like so:

1greet("Alice")

Here, “Alice” is an argument you passed to the greet function. When this line is executed, the string “Alice” is assigned to the name parameter and the function prints “Hello, Alice!”.

Multiple parameters

A function can have multiple parameters which are separated by commas. Here’s an example:

1def add_numbers(num1, num2):
2    print(num1 + num2)

The function add_numbers takes two parameters, num1 and num2, and prints their sum. If you call the function like add_numbers(5, 3), it will output 8.

Note

When calling a function with multiple parameters, the order of arguments should match the order of parameters.

Parameters are local

Parameters in Python are local to the function they are defined in. This means they do not exist outside the function, and any changes to them are not reflected outside the function.

1def show_name(name):
2   name = "Bob"
3   print(name)
4   
5name = "Alice"
6show_name(name)
7print(name)

In the above code, the output will be “Bob” and “Alice”. Although we’ve changed the name variable inside the show_name function, the change does not apply to the global name variable since the parameter is local to the function.

Understanding parameters and arguments is key to mastering Python functions as they enable you to write more flexible and dynamic code that can handle a variety of inputs.