Nearby lessons
70 of 159Python - Function Arguments
- Understand the difference between formal parameters and actual arguments
- Pass values using positional arguments
- Use keyword arguments and default arguments
- Mix positional, keyword and default arguments correctly
- Accept a variable number of values with *args
- Accept a variable number of keyword arguments with **kwargs
Function Parameters and Arguments
Functions become more useful when they can accept input values.
These input values are called Arguments and they are received by the function through Parameters.
Parameters allow the same function to work with different values without changing the function code.
Parameters and Arguments
There are two important terms in Functions:
- Formal Parameters
- Actual Arguments
Formal Parameters
The variables declared inside the function definition are called Formal Parameters.
They receive values from the function call.
Actual Arguments
The values passed while calling a function are called Actual Arguments.
These values are copied into the formal parameters.
Example
Explanation
In the above program:
nameis the Formal Parameter."Durga","Ravi"and"Sunny"are the Actual Arguments.- Every time the function is called, the argument value is assigned to the parameter.
Types of Arguments
Python supports different types of arguments.
- Positional Arguments
- Keyword Arguments
- Default Arguments
- Variable Length Arguments (covered in the next part)
1. Positional Arguments
In Positional Arguments, values are assigned to parameters according to their position.
The first argument is assigned to the first parameter, the second argument to the second parameter, and so on.
Example
Explanation
| Parameter | Argument |
|---|---|
| a | 100 |
| b | 20 |
Since the arguments follow the correct order, the subtraction result is 80.
Changing the Position
Explanation
Because positional arguments depend on their position, changing the order changes the result.
Rules of Positional Arguments
- The number of arguments must match the number of parameters.
- The order of arguments is very important.
- Changing the order changes the result.
2. Keyword Arguments
In Keyword Arguments, values are passed using the parameter names.
Since the parameter name is specified, the order of arguments does not matter.
Syntax
Example 1
Example 2
Explanation
Although the order of the arguments is changed, the output remains the same because values are assigned using parameter names.
Advantages of Keyword Arguments
- Arguments can be supplied in any order.
- Programs become easier to read.
- The possibility of assigning incorrect values is reduced.
Mixing Positional and Keyword Arguments
Python allows positional and keyword arguments to be used together.
However, positional arguments must always come before keyword arguments.
Correct Example
Incorrect Example
Important Rule
Positional arguments must always appear before keyword arguments.
A positional argument cannot appear after a keyword argument.
3. Default Arguments
Sometimes we want a parameter to have a default value.
If the caller does not supply a value, the default value is used automatically.
Syntax
Example
Explanation
During the first function call, no argument is passed.
Therefore, the default value "Guest" is used.
During the remaining calls, the supplied arguments replace the default value.
Rules for Default Arguments
- Default parameters must be declared after non-default parameters.
- A default value is used only when no argument is supplied.
- If an argument is supplied, the default value is ignored.
Correct Example
Incorrect Example
Comparison of Argument Types
| Argument Type | Assignment Method | Order Required |
|---|---|---|
| Positional | Based on position. | Yes |
| Keyword | Based on parameter name. | No |
| Default | Uses predefined value if no argument is supplied. | No |
Introduction to Variable Length Arguments
In the previous section, we learned that a function can receive parameters.
Normally, the number of arguments passed to a function must exactly match the number of formal parameters.
If the number of arguments is different, Python raises an error.
Sometimes, we do not know in advance how many arguments will be passed to a function.
In such situations, Python provides Variable Length Arguments.
Variable Length Arguments allow a function to accept any number of arguments.
Why Do We Need Variable Length Arguments?
Consider a program that calculates the sum of numbers.
Sometimes the user wants to add two numbers, sometimes three numbers, and sometimes ten numbers.
If we use normal parameters, we have to create different functions for every possible case.
This increases code duplication and makes the program difficult to maintain.
Variable Length Arguments solve this problem by allowing a single function to accept any number of values.
Problem with Normal Parameters
Explanation
The function add() is defined with only two parameters:
a, b
The first function call passes two arguments, so it executes successfully.
The second function call passes three arguments.
Since the function expects only two arguments, Python raises a TypeError.
This is one of the biggest limitations of normal parameters.
Solution - Variable Length Arguments
Python provides the * (asterisk) operator to solve this problem.
The * operator allows a function to receive any number of positional arguments.
All the arguments are automatically collected into a single tuple.
Syntax
Syntax Explanation
| Part | Description |
|---|---|
* |
Indicates Variable Length Positional Arguments. |
args |
Stores all arguments inside a tuple. |
| function_name | Name of the function. |
Important Point
The name args is not a keyword.
It is only a naming convention.
You can use any valid variable name after the * operator.
Example
Understanding the Program
Whenever the function is called, Python collects all positional arguments into a tuple.
The tuple is stored inside the variable args.
The number of arguments can be zero, one, two, or any number.
Therefore, the same function works for every function call.
How Python Stores the Arguments
| Function Call | args Value |
|---|---|
display() |
() |
display(10) |
(10,) |
display(10,20) |
(10,20) |
display(10,20,30) |
(10,20,30) |
Real-World Applications
Variable Length Arguments are commonly used in:
- Calculator applications.
- Logging utilities.
- Mathematical operations.
- Data processing utilities.
- Framework development.
Working with *args
In the previous section, we learned that *args collects any number of positional arguments into a tuple.
Now let's understand how to work with *args by using different examples.
Since args is a tuple, we can perform all tuple operations on it such as:
- Traversing
- Indexing
- Finding Length
- Calculating Sum
Example 1 - Print All Arguments
Explanation
All positional arguments are collected into a tuple.
The tuple is printed directly.
The number of arguments can be different in every function call.
Example 2 - Traversing *args
Explanation
Since args is a tuple, we can traverse it by using a for loop.
Each argument is printed one by one.
Example 3 - Count Total Arguments
Explanation
The built-in len() function returns the total number of elements stored in the tuple.
This allows us to determine how many arguments were passed to the function.
Example 4 - Calculate the Sum
Explanation
The parameter numbers stores all arguments as a tuple.
The sum() function calculates the total of all tuple elements.
Example 5 - Find Maximum Value
Explanation
The built-in max() function returns the largest value from the tuple.
Example 6 - Find Minimum Value
Example 7 - Accept Different Data Types
Explanation
*args can store values of different data types because tuples support heterogeneous elements.
How *args Works
| Function Call | Tuple Created |
|---|---|
display() |
() |
display(10) |
(10,) |
display(10,20) |
(10,20) |
display(10,20,30) |
(10,20,30) |
display(10,20,30,40) |
(10,20,30,40) |
Advantages of *args
- Accepts unlimited positional arguments.
- Eliminates the need for multiple overloaded functions.
- Reduces duplicate code.
- Improves code reusability.
- Makes functions flexible.
- Useful when the number of inputs is unknown.
Real-World Applications
- Calculator applications.
- Shopping cart total calculation.
- Statistical calculations.
- Logging systems.
- Data processing libraries.
- Framework development.
Combining Normal Parameters with *args
In the previous section, we learned that *args can accept any number of positional arguments.
Sometimes, a function requires one or more fixed parameters along with additional variable-length arguments.
Python allows us to combine Normal Parameters and *args in the same function.
The fixed values are received by the normal parameters, and all remaining positional arguments are collected into *args.
Syntax
Syntax Explanation
| Part | Description |
|---|---|
| parameter1 | Receives the first positional argument. |
| parameter2 | Receives the second positional argument. |
| *args | Collects all remaining positional arguments into a tuple. |
Example 1 - One Normal Parameter
Explanation
The first argument is assigned to the normal parameter name.
All remaining arguments are collected into the tuple marks.
Example 2 - Two Normal Parameters
Explanation
The first argument is assigned to name.
The second argument is assigned to age.
All remaining arguments are stored inside subjects as a tuple.
Example 3 - Sum of Remaining Numbers
Explanation
The first argument is stored in title.
The remaining numeric values are collected into numbers.
The sum() function calculates the total of all values stored in numbers.
Rules for Combining Normal Parameters and *args
- Normal parameters must appear before
*args. *argsshould be the last positional parameter.- Python first assigns values to the normal parameters.
- All remaining positional arguments are stored in
*args.
Correct Example
How Python Assigns Values
| Argument | Assigned To |
|---|---|
| 10 | a |
| 20 | b |
| 30 | args Tuple |
| 40 | |
| 50 |
Incorrect Example
Why Does This Error Occur?
After *args, every parameter becomes a keyword-only parameter.
Therefore, the parameter a must be supplied using its name.
It cannot receive a positional argument.
Correct Way
Real-World Applications
- Student management systems where a student has a fixed name but variable subjects.
- Billing systems where the customer name is fixed but purchased items vary.
- Employee systems where employee details are fixed but allowances vary.
- Framework APIs that accept mandatory parameters along with optional values.
Introduction to **kwargs
In the previous sections, we learned about *args, which accepts any number of positional arguments.
Python also provides **kwargs, which accepts any number of keyword arguments.
Keyword arguments are passed using the syntax parameter=value.
All keyword arguments are automatically collected into a Dictionary.
Why Do We Need **kwargs?
Sometimes we do not know in advance how many keyword arguments will be passed to a function.
Instead of creating multiple parameters, we can use **kwargs.
This makes the function flexible and reusable.
Syntax
Syntax Explanation
| Part | Description |
|---|---|
** |
Indicates Variable Length Keyword Arguments. |
kwargs |
Stores all keyword arguments in a Dictionary. |
| function_name | Name of the function. |
Important Point
The name kwargs is not a Python keyword.
It is only a naming convention.
You may use any valid variable name after **.
Example 1 - Print Keyword Arguments
Explanation
Each keyword argument is stored as a key-value pair inside the Dictionary kwargs.
The function can receive zero, one, or many keyword arguments.
Example 2 - Traversing **kwargs
Explanation
Since kwargs is a Dictionary, we can use the items() method to traverse all key-value pairs.
Example 3 - Using Normal Parameters with **kwargs
Explanation
The normal parameter name receives the first positional argument.
All keyword arguments are collected into the Dictionary details.
Rules for **kwargs
**kwargsaccepts only keyword arguments.- All keyword arguments are stored in a Dictionary.
- Keys represent parameter names.
- Values represent the supplied values.
- The variable name
kwargscan be replaced with any valid identifier.
Difference Between *args and **kwargs
| Feature | *args | **kwargs |
|---|---|---|
| Accepts | Positional Arguments | Keyword Arguments |
| Data Type | Tuple | Dictionary |
| Symbol | * | ** |
| Access Method | Loop through tuple | Loop through Dictionary |
| Example | fun(10,20,30) |
fun(a=10,b=20) |
Comparison of Normal Parameters, *args and **kwargs
| Feature | Normal Parameter | *args | **kwargs |
|---|---|---|---|
| Accepts | Fixed Arguments | Variable Positional Arguments | Variable Keyword Arguments |
| Data Type | Depends on Value | Tuple | Dictionary |
| Flexibility | Low | High | High |
Real-World Applications
- Configuration settings.
- API development.
- Framework development (Django, Flask, FastAPI).
- Passing optional settings.
- Database configuration.
- Logging utilities.
- Arguments are the values passed to a function and parameters receive them
- Positional arguments must follow position rules and keyword arguments use names
- Default arguments provide fallback values when an argument is omitted
- *args collects extra positional arguments into a tuple
- **kwargs collects extra keyword arguments into a dictionary