6.4 Functions in Python: Function Parameters
Python functions are reusable blocks of code that perform a specific task. They are defined by the 'def' keyword, followed by the function name and parentheses (). Within these parentheses, we can specify the parameters that the function should receive. Parameters are variables that the function uses to perform its task. When we call the function, we supply the values (or arguments) for these parameters.
Defining Functions with Parameters
To define a function with parameters, we enclose parameter variables in parentheses after the function name. For example, the following function has two parameters, 'a' and 'b':
def sum(a, b): return a + b
When we call this function, we need to provide two arguments, which will be used by the function to perform the sum:
result = sum(5, 3) print(result) # Output: 8
Required and Optional Parameters
The parameters of a function can be mandatory or optional. Required parameters must be supplied when calling the function, otherwise Python will return an error. Optional parameters have a default value that will be used if a value is not provided when calling the function.
To make a parameter optional, we include an equal sign (=) and the default value after the parameter name in the function definition. For example, the following function has one required parameter ('a') and one optional parameter ('b'):
def sum(a, b=0): return a + b
When calling this function, we can choose to provide a value for 'b' or not:
print(sum(5)) # Output: 5 print(sum(5, 3)) # Output: 8
Named Parameters
Python also allows us to call a function with named parameters. This means that we can specify which value corresponds to which parameter by name. This can make the code more readable and also allows us to ignore the parameter order.
def greeting(name, greeting="Hello"): return greeting + ", " + name print(greeting(name="Maria", greeting="Good morning")) # Output: Good morning, Maria print(greeting(greeting="Good night", name="John")) # Output: Good night, John
Arbitrary Parameters
Sometimes we don't know in advance how many arguments we'll need to pass to a function. Python allows us to define functions with an arbitrary number of arguments by using the asterisk (*) before the parameter name.
def sum(*numbers): return sum(numbers) print(sum(1, 2, 3, 4, 5)) # Output: 15
In this example, the 'numbers' parameter is a tuple that contains all the arguments given when calling the function.
Understanding how function parameters work in Python is crucial to writing efficient, reusable code. They allow our functions to be flexible and adaptable, able to handle a variety of different input situations.