9.1 Parameters vs Arguments
Newbies often get confused with terms "parameters" and "arguments," but understanding their difference is crucial in functional programming.
Parameters are variables listed in a function definition. They act like placeholders for the values the function will operate on. When defining a function, you're specifying its parameters.
def print_info(name, age): # name and age are parameters
print(f"Name: {name}, Age: {age}")
Arguments are the actual values or data that you pass to a function when calling it. Arguments are substituted into the function's parameters when the function is executed. They can be constants, variables, expressions, or even results of other functions.
print_info("Alice", 30) # "Alice" and 30 are arguments
Types of Arguments
- Positional arguments: Values are passed in the order of the parameters defined.
- Keyword arguments: Arguments provided with the name of the parameter, allowing them to be listed in any order after positional arguments.
- Default arguments: Parameters can be assigned default values in the function definition.
You’re already using positional arguments, but we'll explore keyword and default arguments in upcoming lectures.
The difference between parameters and arguments in Python helps you understand how functions receive and process data. This understanding is crucial for creating flexible functions that can easily adapt to various call conditions, making your code more modular and reusable.
9.2 Default Values
Default arguments in Python allow functions to have pre-set values for one or more parameters, making function calls more convenient and flexible as you don’t need to explicitly pass all arguments every time.
Defining Default Arguments
Default arguments are set in the function definition where the parameter is declared with a value to be used if no argument is passed when calling the function:
def print_info(name, company='Unknown'):
print(f"Name: {name}, Company: {company}")
In this example, company has a default value of 'Unknown'.
- Simplifying function calls: Functions with numerous parameters can be called with just the most crucial arguments.
- Flexibility: Functions can be adapted to different scenarios without altering their code.
- Code readability: Explicit default values make the code self-documenting.
Important Nuances
Immutability: Default argument values should be immutable types like numbers, strings, or tuples. Using mutable types (like lists or dictionaries) can lead to unexpected side effects as modifications in these objects persist between function calls.
Order of arguments: Parameters with default arguments should follow after parameters without default arguments in the function definition.
Another example:
def create_user(username, is_admin=False):
if is_admin:
print(f"User {username} is an admin.")
else:
print(f"User {username} is a regular user.")
create_user("Alice") # is_admin == False
create_user("Bob", is_admin=True) # is_admin == True
create_user("Karl", True) # is_admin == True
Above are 3 ways to call a function with a default argument: each is valid.
9.3 Passing Parameters by Name
Passing parameters by name in a function makes it clear what values are being assigned to which parameters, improving readability and reducing errors related to incorrect argument order.
To pass a parameter by name, you assign a value to a specific parameter when calling the function:
function(parameter1 = value, parameter2 = value)
This approach is especially useful with functions that have many parameters or parameters with default values.
Benefits of Passing Parameters by Name
- Clarity and readability: Specifying parameter names on function calls makes code easier for others to understand or when revisiting your own old code.
- Flexibility: Parameters can be passed in any order, which is convenient when a function has many parameters.
- Avoiding errors: No need to remember the parameter order, reducing errors related to incorrect value assignment.
Usage Examples
def create_profile(name, age, job):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Job: {job}")
create_profile(age = 28, name = "John", job = "Developer")
In this example, parameters are passed not in a sequence but each is explicitly assigned a value, making the function call more flexible and understandable.
Example 2:
By the way, you've encountered named parameter passing before. Remember the print() function?
print(1, 2, 3, 4, 5, sep="-", end="!!")
Yes, this is exactly the case 😊
Features and Limitations
Parameters passed by name must follow after unnamed parameters, if there are any in the function definition.
You cannot use the same parameter name more than once in a function call.
Passing parameters by name is a powerful feature in Python that makes your code safer and more understandable, especially in cases involving functions with many arguments or optional values.
GO TO FULL VERSION