Understanding Positional, Keyword, and Default Arguments in Python
Course: Python Training
Topic: Understanding Positional, Keyword, and Default Arguments
Course Link: Python Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Function Arguments
In Python, functions are reusable blocks of code that perform specific tasks. Functions often require input values to work with, and these values are passed through arguments. Understanding how arguments work helps developers create flexible, readable, and reusable programs.
Python supports different ways of passing arguments to functions. Three important types are positional arguments, keyword arguments, and default arguments. Each type provides a different way to supply values to parameters.
- Positional arguments: Values are assigned to parameters according to their position in the function call.
- Keyword arguments: Values are assigned using parameter names.
- Default arguments: Parameters use predefined values when corresponding arguments are not supplied.
Learning Objectives
- Understand the difference between parameters and arguments.
- Learn how positional arguments work.
- Pass values using keyword arguments.
- Define and use default parameter values.
- Combine different argument types correctly.
- Identify common argument-related errors.
- Apply argument concepts to practical Python programs.
2. Understanding Parameters and Arguments
Although the terms parameters and arguments are often used interchangeably in conversation, they have different meanings in Python.
A parameter is a variable specified in a function definition. An argument is the actual value supplied when the function is called.
Example
def greet(name):
print("Hello,", name)
greet("Aarav")
Output:
Hello, Aarav
Explanation:
name is the parameter.
"Aarav" is the argument.
greet("Aarav") calls the function.
- Python assigns the supplied value to the parameter and executes the function body.
General Syntax
def function_name(parameter1, parameter2):
# Function body
statements
function_name(argument1, argument2)
Parameters define what information a function can receive. Arguments provide the information needed for a particular function call.
3. What Are Positional Arguments?
Positional arguments are values passed to a function in the same order as the parameters appear in the function definition. Python matches each value to its corresponding parameter based on position.
Example 1: Basic Positional Arguments
def student_details(name, age):
print("Name:", name)
print("Age:", age)
student_details("Riya", 21)
Output:
Name: Riya
Age: 21
Explanation: The first argument, "Riya", is assigned to name. The second argument, 21, is assigned to age.
Example 2: Multiple Positional Arguments
def calculate_total(price, quantity, tax):
total = price * quantity
final_total = total + (total * tax / 100)
return final_total
result = calculate_total(500, 2, 18)
print("Final Total:", result)
Output:
Final Total: 1180.0
Explanation:
price receives 500.
quantity receives 2.
tax receives 18.
- The subtotal is 1000, and 18% tax is 180.
- The final amount is 1180.
Example 3: Order Matters
def describe_person(name, city):
print(name, "lives in", city)
describe_person("Mumbai", "Aarav")
Output:
Mumbai lives in Aarav
The output is technically valid, but the values have been supplied in the wrong order for the intended meaning. Python does not automatically determine which value represents a name or a city.
Correct call:
describe_person("Aarav", "Mumbai")
Output:
Aarav lives in Mumbai
Advantages of Positional Arguments
- Simple and concise for functions with a small number of parameters.
- Easy to use when the order of values is obvious.
- Useful for mathematical functions and straightforward operations.
Limitations of Positional Arguments
- The order of arguments must be correct.
- Calls with many parameters can become difficult to understand.
- Swapping values of similar types may cause logical errors without raising an exception.
4. What Are Keyword Arguments?
Keyword arguments are values passed to a function by explicitly specifying parameter names. Instead of relying only on position, Python matches each argument to the parameter identified by its keyword.
Syntax
function_name(parameter1=value1, parameter2=value2)
Example 1: Using Keyword Arguments
def student_details(name, age, course):
print("Name:", name)
print("Age:", age)
print("Course:", course)
student_details(
course="Python",
name="Meera",
age=22
)
Output:
Name: Meera
Age: 22
Course: Python
Explanation: The arguments are supplied in a different order from the function definition. Because each value is associated with a parameter name, Python assigns the values correctly.
Example 2: Improve Readability with Keywords
def book_ticket(destination, passengers, travel_class):
print("Destination:", destination)
print("Passengers:", passengers)
print("Class:", travel_class)
book_ticket(
destination="Delhi",
passengers=3,
travel_class="Business"
)
Output:
Destination: Delhi
Passengers: 3
Class: Business
Keyword arguments make the function call easier to understand because each supplied value is clearly associated with its meaning.
Example 3: Mixing Positional and Keyword Arguments
def employee_details(name, department, salary):
print("Name:", name)
print("Department:", department)
print("Salary:", salary)
employee_details("Karan", salary=45000, department="IT")
Output:
Name: Karan
Department: IT
Salary: 45000
Positional arguments can be combined with keyword arguments. However, positional arguments must come before keyword arguments in a function call.
Invalid example:
# This raises a SyntaxError:
# employee_details(name="Karan", "IT", salary=45000)
Correct alternatives:
employee_details("Karan", "IT", 45000)
employee_details(
name="Karan",
department="IT",
salary=45000
)
Advantages of Keyword Arguments
- Improve code readability.
- Allow arguments to be supplied in a different order.
- Reduce confusion when a function has several parameters.
- Make function calls easier to maintain.
Limitations of Keyword Arguments
- Keyword names must match the function's parameter names.
- Passing the same parameter more than once causes an error.
- They can make very simple function calls unnecessarily verbose if overused.
5. What Are Default Arguments?
Default arguments are values assigned to parameters in the function definition. If the caller does not provide a value for a parameter with a default, Python uses the predefined value.
Default arguments are useful when a function has common or optional settings, such as a default language, tax rate, greeting, discount, or page size.
Syntax
def function_name(parameter=default_value):
# Function body
statements
Example 1: Simple Default Argument
def greet(name="Guest"):
print("Hello,", name)
greet()
greet("Aarav")
Output:
Hello, Guest
Hello, Aarav
Explanation:
- When
greet() is called without an argument, the default value "Guest" is used.
- When
greet("Aarav") is called, the supplied value replaces the default for that call.
Example 2: Multiple Default Arguments
def course_details(course="Python", duration="3 months", mode="Online"):
print("Course:", course)
print("Duration:", duration)
print("Mode:", mode)
course_details()
print("---")
course_details("Data Analytics", "6 months", "Classroom")
Output:
Course: Python
Duration: 3 months
Mode: Online
---
Course: Data Analytics
Duration: 6 months
Mode: Classroom
All three parameters have defaults, so the function can be called without arguments or with replacement values.
Example 3: Overriding One Default Value
def order_summary(product, quantity=1, delivery="Standard"):
print("Product:", product)
print("Quantity:", quantity)
print("Delivery:", delivery)
order_summary("Keyboard")
print("---")
order_summary("Mouse", quantity=2)
print("---")
order_summary("Monitor", quantity=1, delivery="Express")
Output:
Product: Keyboard
Quantity: 1
Delivery: Standard
---
Product: Mouse
Quantity: 2
Delivery: Standard
---
Product: Monitor
Quantity: 1
Delivery: Express
In the first call, both optional parameters use their defaults. In the second call, only the quantity is changed. In the third call, both optional values are supplied explicitly.
Important Rule: Required Parameters Before Default Parameters
In a regular function definition, parameters without defaults must appear before parameters with defaults.
Incorrect:
# This raises a SyntaxError:
# def calculate(price=100, quantity):
# return price * quantity
Correct:
def calculate(quantity, price=100):
return price * quantity
print(calculate(3))
print(calculate(3, 200))
Output:
300
600
Here, quantity is required and price is optional.
6. Comparison of Positional, Keyword, and Default Arguments
| Feature |
Positional Arguments |
Keyword Arguments |
Default Arguments |
| How values are assigned |
By position |
By parameter name |
Uses a predefined value if omitted |
| Must a value be supplied? |
Usually, if the parameter has no default |
Usually, if the parameter has no default |
No, if the parameter has a default |
| Order sensitivity |
Yes |
Keyword order can vary |
Depends on how the function is called |
| Readability |
Good for simple calls |
Good for functions with many parameters |
Provides sensible fallback values |
| Example |
greet("Riya") |
greet(name="Riya") |
def greet(name="Guest"): |
Combined Example
def calculate_bill(price, quantity=1, discount=0):
subtotal = price * quantity
discount_amount = subtotal * discount / 100
return subtotal - discount_amount
print(calculate_bill(1000))
print(calculate_bill(1000, 2))
print(calculate_bill(price=1000, quantity=2, discount=10))
print(calculate_bill(500, discount=20))
Output:
1000.0
2000.0
1800.0
400.0
This example demonstrates required positional input, default values, and keyword arguments in the same function.
7. Practical Example: Student Grade Calculator
A student grade calculator can use positional arguments for marks and default arguments for the passing threshold. Keyword arguments make the function call easier to understand.
def calculate_result(name, marks, passing_marks=40):
print("Student:", name)
print("Marks:", marks)
print("Passing Marks:", passing_marks)
if marks >= passing_marks:
print("Result: Pass")
else:
print("Result: Fail")
calculate_result("Riya", 78)
print("---")
calculate_result(name="Aarav", marks=32, passing_marks=35)
Output:
Student: Riya
Marks: 78
Passing Marks: 40
Result: Pass
---
Student: Aarav
Marks: 32
Passing Marks: 35
Result: Fail
Explanation:
name and marks are required parameters.
passing_marks has a default value of 40.
- The first call uses the default passing threshold.
- The second call uses keyword arguments and overrides the passing threshold to 35.
- The function compares the marks with the threshold and displays the result.
8. Practical Example: Product Price Calculator
This example calculates the final price after applying an optional discount and tax rate.
def final_price(price, quantity=1, discount=0, tax=18):
subtotal = price * quantity
discounted_price = subtotal - (subtotal * discount / 100)
total = discounted_price + (discounted_price * tax / 100)
return round(total, 2)
print(final_price(1000))
print(final_price(1000, quantity=2))
print(final_price(1000, quantity=2, discount=10, tax=5))
print(final_price(price=500, discount=20, tax=0))
Output:
1180.0
2360.0
1890.0
400.0
Explanation: The function uses the supplied price and quantity to calculate the subtotal. It applies the discount before calculating tax. If quantity, discount, or tax is omitted, the function uses the corresponding default value.
For production use, additional validation should ensure that price and quantity are non-negative and that discount and tax percentages fall within acceptable ranges.
9. Common Errors and How to Fix Them
Error 1: Missing a Required Argument
def add(a, b):
return a + b
# Incorrect:
# add(10)
Problem: The function requires two arguments, but only one is supplied. Python raises a TypeError.
Solution: Supply both arguments or define a default for a parameter if that makes sense for the function.
print(add(10, 20))
Error 2: Supplying Too Many Positional Arguments
def greet(name):
print("Hello,", name)
# Incorrect:
# greet("Riya", "Aarav")
Problem: The function accepts one argument but receives two.
Solution: Pass only the expected number of arguments or redesign the function to accept multiple values if required.
Error 3: Providing a Parameter Twice
def display(name, age):
print(name, age)
# Incorrect:
# display("Riya", name="Aarav", age=21)
Problem: The parameter name receives a value both positionally and by keyword, causing a TypeError.
Correct version:
display("Riya", age=21)
Error 4: Positional Argument After a Keyword Argument
# Incorrect:
# display(name="Riya", 21)
Problem: A positional argument cannot follow a keyword argument in a function call.
Correct version:
display("Riya", 21)
Alternatively, use keywords for both values: display(name="Riya", age=21).
Error 5: Incorrect Default Parameter Order
# Incorrect:
# def register(course="Python", name):
# pass
Problem: A required parameter cannot follow a default parameter in this type of function definition.
Correct version:
def register(name, course="Python"):
print(name, course)
register("Meera")
Error 6: Using a Mutable Object as a Default
Default values are evaluated when the function is defined, not every time it is called. Using a mutable default such as a list can therefore cause data to be shared across calls.
Problematic example:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("Pen"))
print(add_item("Book"))
Output:
['Pen']
['Pen', 'Book']
The same list is reused across calls, which may not be the intended behavior.
Recommended solution: Use None as the default and create a new list inside the function.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("Pen"))
print(add_item("Book"))
Output:
['Pen']
['Book']
10. Best Practices for Function Arguments
- Use positional arguments for short function calls where parameter order is easy to understand.
- Use keyword arguments when a function has multiple parameters or when clarity matters.
- Choose meaningful default values that represent sensible behavior.
- Place required parameters before default parameters in a function definition.
- Avoid mutable objects such as lists and dictionaries as defaults unless shared state is intentional.
- Validate arguments when invalid values could lead to incorrect calculations or unexpected behavior.
- Use keyword arguments to make calls more self-documenting, especially when passing Boolean values or configuration options.
- Keep function signatures simple and avoid unnecessary parameters.
- Write docstrings to explain required inputs, optional parameters, default values, and return values.
- Test functions with normal inputs, missing optional inputs, boundary values, and invalid inputs.
11. Practice Exercises
Exercise 1: Create a Greeting Function
Create a function that accepts a person's name and displays a greeting. Use a default value of "Guest".
def greet(name="Guest"):
print("Welcome,", name)
greet()
greet("Meera")
Expected Output:
Welcome, Guest
Welcome, Meera
Exercise 2: Calculate an Area
Create a function that calculates the area of a rectangle using length and width. Give width a default value of 5.
def rectangle_area(length, width=5):
return length * width
print(rectangle_area(10))
print(rectangle_area(10, 8))
Expected Output:
50
80
Exercise 3: Display Employee Details
Create a function with parameters for name, department, and salary. Call it using keyword arguments in a different order.
def employee(name, department, salary):
print("Name:", name)
print("Department:", department)
print("Salary:", salary)
employee(salary=50000, name="Karan", department="Development")
Expected Output:
Name: Karan
Department: Development
Salary: 50000
Exercise 4: Calculate a Discount
Create a function that accepts a price and an optional discount percentage. The default discount should be zero.
def discounted_price(price, discount=0):
return price - (price * discount / 100)
print(discounted_price(1000))
print(discounted_price(1000, 15))
Expected Output:
1000.0
850.0
Exercise 5: Build a Course Registration Function
Create a function with a required student name and a course parameter that defaults to Python. Use both positional and keyword calls.
def register_student(name, course="Python"):
print(name, "registered for", course)
register_student("Riya")
register_student(name="Aarav", course="Data Analytics")
Expected Output:
Riya registered for Python
Aarav registered for Data Analytics
12. Interview Questions and Answers
Q1. What are positional arguments in Python?
Answer: Positional arguments are assigned to parameters according to their order in the function call.
Q2. What are keyword arguments?
Answer: Keyword arguments are passed by specifying parameter names, allowing values to be matched to the correct parameters without depending solely on their order.
Q3. What are default arguments?
Answer: Default arguments are parameters with predefined values. Python uses the default when the caller does not supply a value for that parameter.
Q4. Can positional and keyword arguments be used together?
Answer: Yes. Positional arguments must appear before keyword arguments in a function call. A parameter must not receive more than one value.
Q5. Why are keyword arguments useful?
Answer: They improve readability, clarify the meaning of values, and allow arguments to be supplied in a different order from the parameter definition.
Q6. What happens when a required argument is missing?
Answer: Python generally raises a TypeError indicating that a required positional or keyword argument is missing.
Q7. Can a default argument be overridden?
Answer: Yes. A caller can supply a value for a parameter that has a default, and Python uses the supplied value for that call.
Q8. Why should mutable default arguments be avoided?
Answer: Mutable defaults are created once when the function is defined and can retain changes across calls. Using None and creating a new object inside the function avoids unintended shared state.
Q9. Can keyword arguments be passed in any order?
Answer: Yes, provided each keyword matches a valid parameter and no parameter receives multiple values.
Q10. What is the difference between a parameter and an argument?
Answer: A parameter is a variable listed in a function definition. An argument is the value supplied to that function when it is called.
13. Quick Revision Checklist
- Positional arguments are matched by order.
- Keyword arguments are matched by parameter name.
- Default arguments provide values when optional inputs are omitted.
- Required parameters should appear before default parameters.
- Positional arguments must come before keyword arguments in a function call.
- A parameter cannot receive multiple values in the same call.
- Mutable default values can persist across function calls.
- Using
None as a default is a common way to avoid unintended shared mutable state.
- Keyword arguments can make complex function calls easier to read.
- Practice with calculations, student records, employee details, and configurable functions.
14. Conclusion
Positional, keyword, and default arguments are fundamental concepts in Python function design. Positional arguments provide a concise way to pass values in order, keyword arguments make function calls clearer, and default arguments allow functions to work with optional inputs.
Understanding these concepts helps you build functions that are readable, flexible, and easier to maintain. Practise combining all three argument types, handling missing inputs, and avoiding common errors to strengthen your Python programming skills.
Continue Learning: Explore the Python Training Course, register for a course demo, or visit the JustAcademy website.