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:
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:
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:
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.
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.