Single Parameter Example
Consider a function that multiplies the user’s input by a given value. In the example below, the functioninput_number has a single parameter named num. When calling this function, you supply an argument (in this case, 10), which is assigned to num. The function then multiplies the user’s input by this value.
12, the function calculates 12 × 10, resulting in 120.
Multiple Parameters in Functions
A function can accept multiple parameters that are separated by commas. The order in which you pass the arguments is important because the first argument is assigned to the first parameter, the second to the second, and so on. For example:num1 receives the value 10, and num2 receives 20. So if the user inputs 12, the function computes 12 × 10 and then subtracts 20, resulting in 100.
Utilizing Named Parameters
To reduce dependency on the order of arguments, you can use named parameters when calling a function. This approach enables you to explicitly assign values to specific parameters, even if they are provided in a different order. For example, to swap the values assigned tonum1 and num2, you can call the function like this:
Avoid assigning a value to the same parameter more than once. For example, providing
num1 both positionally and by name will result in an error:Default Parameter Values
Python also allows you to define default values for parameters. When calling the function, if the caller does not supply an argument for a parameter with a default value, Python automatically uses that default. For instance, if we set the default value ofnum to 10, the function will multiply the user’s input by 10 if no argument is provided:
That’s the end of our discussion on passing arguments to Python functions. It’s time to get hands-on and practice these concepts. For further reading on Python functions, consider visiting the Python Documentation.