Python Function Parameters
In Python, function parameters allow you to pass information into a function so that it can process and return output based on those inputs. Knowing how to use parameters will enable you to write more flexible, reusable, and clean code.
There are different types of function parameters, such as:
- Positional Parameters: Parameters that must be passed in a specific order.
- Default Parameters: Parameters that have a default value if not provided when the function is called.
- Keyword Parameters: Parameters passed by name, allowing you to specify their values in any order.
- Variable-Length Parameters: Parameters that can accept any number of arguments (using `*args` and `**kwargs`).
What You'll Learn
You will learn how to define functions with parameters, how to pass values to these parameters, and how to handle different types of parameters, including default and variable-length parameters.
Positional Parameters
Positional parameters are the most common way to pass values into functions. These parameters must be provided in the exact order in which they are defined in the function.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Tom", 25)
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Tom", 25)
How It Works:
- greet: The name of the function you're calling.
- "Tom": This is passed to the name parameter.
- 25: This is passed to the age parameter.
- When the code is run, Python matches the provided values to the parameters in the function definition, in the correct order.
Output
Hello Tom, you are 25 years old.
Hello Tom, you are 25 years old.
Default Parameters
Default parameters allow you to assign default values to function parameters. If a value is not provided for a parameter when the function is called, the default value is used instead.
def greet(name, age=30):
print(f"Hello {name}, you are {age} years old.")
greet("Jack") # Uses default age
greet("Tom", 25) # Overrides default age
def greet(name, age=30):
print(f"Hello {name}, you are {age} years old.")
greet("Jack") # Uses default age
greet("Tom", 25) # Overrides default age
How It Works:
- age=30: This sets a default value for the age parameter.
- If the function is called with only the name, the default age of 30 will be used.
- If both arguments are provided, the default value is overridden by the second argument.
Output
Hello Jack, you are 30 years old.
Hello Tom, you are 25 years old.
Hello Jack, you are 30 years old.
Hello Tom, you are 25 years old.
Keyword Parameters
Keyword parameters allow you to specify the values of parameters by name. This gives you the flexibility to pass arguments in any order, as long as you use the parameter names.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=30, name="Charlie") # Pass parameters in any order
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=30, name="Charlie") # Pass parameters in any order
How It Works:
- Using name="Charlie" and age=30 allows you to pass parameters in any order, making your code more readable and flexible.
- Python matches the parameters with the values based on the keyword (parameter name), not the order.
Output
Hello Charlie, you are 30 years old.
Hello Charlie, you are 30 years old.
Variable-Length Parameters
You can also define functions that accept a variable number of arguments using *args and **kwargs. *args allows you to pass a variable number of positional arguments, while **kwargs allows you to pass a variable number of keyword arguments.
Passing a variable number of positional arguments using *args.
def greet(*names):
for name in names:
print(f"Hello {name}")
greet("Tom", "Jack", "Charlie")
def greet(*names):
for name in names:
print(f"Hello {name}")
greet("Tom", "Jack", "Charlie")
How It Works:
- *names: This allows you to pass any number of positional arguments, which will be stored in a tuple named names.
- The function then iterates through the tuple and prints a greeting for each name passed.
Output
Hello Tom
Hello Jack
Hello Charlie
Hello Tom
Hello Jack
Hello Charlie
Passing a variable number of keyword arguments using **kwargs. This is useful when you need to handle multiple named parameters dynamically.
def describe_person(**info):
for key, value in info.items():
print(f"{key}: {value}")
describe_person(name="Tom", age=25, job="Engineer")
def describe_person(**info):
for key, value in info.items():
print(f"{key}: {value}")
describe_person(name="Tom", age=25, job="Engineer")
How It Works (with **kwargs):
- **info: This allows you to pass any number of keyword arguments, which are stored in a dictionary named info.
- The function then iterates through the dictionary and prints each key-value pair.
Output
name: Tom
age: 25
job: Engineer
name: Tom
age: 25
job: Engineer
Frequently Asked Questions
What are parameters in Python functions?
What are parameters in Python functions?
Parameters are variables used inside a function definition to accept input values. They allow your functions to work with dynamic data and increase reusability.
What is the difference between *args and **kwargs?
What is the difference between *args and **kwargs?
*args lets you handle a variable number of positional arguments as a tuple, while **kwargs handles keyword arguments as a dictionary.
Can I mix positional and keyword parameters in a function?
Can I mix positional and keyword parameters in a function?
Yes, Python allows you to combine both. Just make sure that positional arguments come before keyword arguments in the function call.
What is a default parameter?
What is a default parameter?
A default parameter is a parameter with a predefined value. If the caller does not provide a value for it, Python uses the default.
What happens if I provide more arguments than parameters?
What happens if I provide more arguments than parameters?
If your function doesn’t account for extra inputs using *args or **kwargs, Python will raise a TypeError.
What's Next?
Next, you'll learn about Python's return statement, which is used to send back a result from a function. The return statement allows you to pass values out of a function so you can use them elsewhere in your code. It's an essential concept for creating reusable, modular code and working with functions that perform calculations or process data.