Function parameters are the inputs that a function receives when it is called. There are two types of function parameters in Python: positional parameters and keyword parameters.
Positional parameters are passed to a function in the order that they appear in the function definition. Here's an example:
def add_numbers(x, y): return x + yresult = add_numbers(3, 4)print(result) # Output: 7 |
In this example, the add_numbers function takes two positional parameters, x and y. When the function is called with add_numbers(3, 4), the value 3 is assigned to x and the value 4 is assigned to y.
Keyword parameters are passed to a function using their names, and can be used to specify default values for parameters. Here's an example:
def greet(name='world', greeting='Hello'): print(f'{greeting}, {name}!')greet() # Output: Hello, world!greet('Alice') # Output: Hello, Alice!greet(greeting='Hi', name='Bob') # Output: Hi, Bob! |
In this example, the greet function has two keyword parameters, name and greeting, with default values of 'world' and 'Hello', respectively. When the function is called without any arguments, it uses the default values. When the function is called with positional arguments, they are assigned in order to the parameters. When the function is called with keyword arguments, they are assigned by name, and can be provided in any order.
You can also use both positional and keyword parameters in the same function call:
|
def add_numbers(x, y, z=0): return x + y + z result = add_numbers(1, 2, z=3) print(result) # |
Output: 6 In this example, the add_numbers function takes two positional parameters, x and y, and one keyword parameter, z, with a default value of 0. When the function is called with add_numbers(1, 2, z=3), the value 1 is assigned to x, the value 2 is assigned to y, and the value 3 is assigned to z.