Nearby lessons

70 of 159

Python - Function Arguments

📌 What You Will Learn
  • 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

🐍Code Cell
1def wish(name):
2 print("Hello", name)
3 
4wish("Durga")
5 
6wish("Ravi")
7 
8wish("Sunny")
Output
Hello Durga
Hello Ravi
Hello Sunny

Explanation

In the above program:

  • name is 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.

  1. Positional Arguments
  2. Keyword Arguments
  3. Default Arguments
  4. 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

🐍Code Cell
1def sub(a, b):
2 print(a - b)
3 
4sub(100, 20)
Output
80

Explanation

Parameter Argument
a 100
b 20

Since the arguments follow the correct order, the subtraction result is 80.

Changing the Position

🐍Code Cell
1def sub(a, b):
2 print(a - b)
3 
4sub(20, 100)
Output
-80

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

🐍Code Cell
1function_name(parameter=value)
Output
No output captured.

Example 1

🐍Code Cell
1def wish(name, msg):
2 print("Hello", name, msg)
3 
4wish(name="Durga", msg="Good Morning")
Output
Hello Durga Good Morning

Example 2

🐍Code Cell
1def wish(name, msg):
2 print("Hello", name, msg)
3 
4wish(msg="Good Morning", name="Durga")
Output
Hello Durga Good Morning

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

🐍Code Cell
1def wish(name, msg):
2 print("Hello", name, msg)
3 
4wish("Durga", msg="Good Morning")
Output
Hello Durga Good Morning

Incorrect Example

🐍Code Cell
1def wish(name, msg):
2 print("Hello", name, msg)
3 
4wish(name="Durga", "Good Morning")
Output
SyntaxError:
Positional argument follows keyword argument

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

🐍Code Cell
1def function_name(parameter=default_value):
2 statements
Output
No output captured.

Example

🐍Code Cell
1def wish(name="Guest"):
2 print("Hello", name)
3 
4wish()
5 
6wish("Durga")
7 
8wish("Ravi")
Output
Hello Guest
Hello Durga
Hello Ravi

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

🐍Code Cell
1def student(name, marks=0):
2 print(name, marks)
Output
No output captured.

Incorrect Example

🐍Code Cell
1def student(name="Guest", marks):
2 print(name, marks)
Output
SyntaxError:
non-default argument follows default argument

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

🐍Code Cell
1def add(a, b):
2 print(a + b)
3 
4add(10, 20)
5 
6add(10, 20, 30)
Output
30

TypeError:
add() takes 2 positional arguments but 3 were given

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

🐍Code Cell
1def function_name(*args):
2 statements
Output
No output captured.

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

🐍Code Cell
1def display(*args):
2 print(args)
3 
4display()
5 
6display(10)
7 
8display(10, 20)
9 
10display(10, 20, 30)
Output
()
(10,)
(10, 20)
(10, 20, 30)

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

🐍Code Cell
1def display(*args):
2 print(args)
3 
4display(10, 20, 30, 40)
5 
6display("Python", "Java", "C++")
Output
(10, 20, 30, 40)
('Python', 'Java', 'C++')

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

🐍Code Cell
1def display(*args):
2 for value in args:
3 print(value)
4 
5display(10, 20, 30, 40)
Output
10
20
30
40

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

🐍Code Cell
1def display(*args):
2 print("Total Arguments =", len(args))
3 
4display()
5 
6display(10)
7 
8display(10, 20)
9 
10display(10, 20, 30, 40, 50)
Output
Total Arguments = 0
Total Arguments = 1
Total Arguments = 2
Total Arguments = 5

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

🐍Code Cell
1def add(*numbers):
2 print(sum(numbers))
3 
4add(10, 20)
5 
6add(10, 20, 30)
7 
8add(10, 20, 30, 40, 50)
Output
30
60
150

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

🐍Code Cell
1def maximum(*numbers):
2 print(max(numbers))
3 
4maximum(10, 30, 20)
5 
6maximum(100, 50, 70, 90)
Output
30
100

Explanation

The built-in max() function returns the largest value from the tuple.

Example 6 - Find Minimum Value

🐍Code Cell
1def minimum(*numbers):
2 print(min(numbers))
3 
4minimum(10, 30, 20)
5 
6minimum(100, 50, 70, 90)
Output
10
50

Example 7 - Accept Different Data Types

🐍Code Cell
1def display(*args):
2 for value in args:
3 print(value)
4 
5display(
6 100,
7 "Python",
8 10.5,
9 True
10)
Output
100
Python
10.5
True

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

🐍Code Cell
1def function_name(parameter1, parameter2, *args):
2 statements
Output
No output captured.

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

🐍Code Cell
1def display(name, *marks):
2 print("Name :", name)
3 print("Marks :", marks)
4 
5display("Rahul", 80, 90, 95)
6 
7display("Neha", 70, 75)
Output
Name : Rahul
Marks : (80, 90, 95)
Name : Neha
Marks : (70, 75)

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

🐍Code Cell
1def student(name, age, *subjects):
2 print("Name :", name)
3 print("Age :", age)
4 print("Subjects :", subjects)
5 
6student("Rahul", 20, "Python", "Java", "React")
Output
Name : Rahul
Age : 20
Subjects : ('Python', 'Java', 'React')

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

🐍Code Cell
1def total(title, *numbers):
2 print(title)
3 print("Sum =", sum(numbers))
4 
5total("Addition of Numbers", 10, 20, 30, 40)
6 
7total("Another Example", 5, 10, 15)
Output
Addition of Numbers
Sum = 100
Another Example
Sum = 30

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.
  • *args should be the last positional parameter.
  • Python first assigns values to the normal parameters.
  • All remaining positional arguments are stored in *args.

Correct Example

🐍Code Cell
1def demo(a, b, *args):
2 print(a)
3 print(b)
4 print(args)
5 
6demo(10, 20, 30, 40, 50)
Output
10
20
(30, 40, 50)

How Python Assigns Values

Argument Assigned To
10 a
20 b
30 args Tuple
40
50

Incorrect Example

🐍Code Cell
1def demo(*args, a):
2 print(args)
3 print(a)
4 
5demo(10, 20, 30)
Output
TypeError:
missing required keyword-only argument: 'a'

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

🐍Code Cell
1def demo(*args, a):
2 print(args)
3 print(a)
4 
5demo(10, 20, 30, a=40)
Output
(10, 20, 30)
40

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

🐍Code Cell
1def function_name(**kwargs):
2 statements
Output
No output captured.

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

🐍Code Cell
1def display(**kwargs):
2 print(kwargs)
3 
4display()
5 
6display(name="Durga")
7 
8display(name="Durga", age=35)
9 
10display(name="Durga", age=35, city="Hyderabad")
Output
{}
{'name': 'Durga'}
{'name': 'Durga', 'age': 35}
{'name': 'Durga', 'age': 35, 'city': 'Hyderabad'}

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

🐍Code Cell
1def display(**kwargs):
2 for k, v in kwargs.items():
3 print(k, "=", v)
4 
5display(
6 name="Rahul",
7 age=20,
8 course="Python"
9)
Output
name = Rahul
age = 20
course = Python

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

🐍Code Cell
1def student(name, **details):
2 print("Name :", name)
3 print("Details :", details)
4 
5student(
6 "Rahul",
7 age=20,
8 city="Delhi",
9 course="Python"
10)
Output
Name : Rahul
Details : {'age': 20, 'city': 'Delhi', 'course': 'Python'}

Explanation

The normal parameter name receives the first positional argument.

All keyword arguments are collected into the Dictionary details.

Rules for **kwargs

  • **kwargs accepts only keyword arguments.
  • All keyword arguments are stored in a Dictionary.
  • Keys represent parameter names.
  • Values represent the supplied values.
  • The variable name kwargs can 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.
📝 Key Takeaways
  • 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

🧠 Test Your Knowledge

33 Questions
Progress: 0 / 33