What are parameters?
Parameters let you pass data into functions. Instead of hardcoding values, you make functions flexible to work with different inputs.Basic parameters
Add parameters inside the parentheses when defining a function:The values you pass when calling a function are called “arguments”. The variables in the function definition are “parameters”. Many people use these terms interchangeably.
Positional arguments
By default, Python matches the arguments you pass in a function call to the parameters in the function definition by their position (order).Multiple parameters
Functions can have multiple parameters of any type:Default values
Give parameters default values for optional arguments:Keyword arguments
Call functions using parameter names for clarity:Mixing positional and keyword arguments
You can combine positional and keyword arguments in the same function call. This is useful when you want to provide values for the first few parameters positionally, and use keyword names for the rest.Key rules to remember
Here is a quick summary of rules for parameters and arguments:-
Order in Function Definition:
- Always place required parameters (without default values) before optional parameters (with default values).
def greet(name, greeting="Hello")is correct.def greet(greeting="Hello", name)is incorrect (will raise aSyntaxError).
-
Order in Function Calls:
- Positional arguments must always come before keyword arguments.
greet("Alice", greeting="Hi")is correct.greet(name="Alice", "Hi")is incorrect (will raise aSyntaxError).
-
No Double Assignment:
- You cannot pass multiple values for the same parameter in a single call.
greet("Alice", name="Bob")is incorrect (will raise aTypeError).
-
Beware of Mutable Defaults:
- Never use mutable types (like lists
[]or dictionaries{}) as default parameters. UseNoneinstead.
- Never use mutable types (like lists
Common mistakes
Wrong number of arguments
Wrong number of arguments
Default values with mutable objects
Default values with mutable objects
What’s next?
Functions become truly powerful when they can return values. Let’s learn how!Return values
Get results from functions