๐๏ธ What are Function Arguments in Python?
Arguments are the values passed into a function when it is called.
Python supports a flexible array of argument typesโincluding standard positional arguments, named keyword arguments, default fallback values, variable-length tuples (*args), and variable-length dictionaries (**kwargs)โgiving developers total control over function interfaces.
1. Positional Arguments
Positional arguments must be supplied in the exact order specified in the function definition.
Python
def calculate_rectangle_area(length, width):
return length * width
# Arguments are mapped positionally: length=10, width=5
area = calculate_rectangle_area(10, 5)
print("Calculated Area:", area)
Output:
Calculated Area: 50
Real-Time Example 1: Keyword Arguments
Pass arguments by explicitly naming parameters during the function call, bypassing strict positional order.
Python
def create_user_profile(username, role, status):
print(f"User: {username} | Role: {role} | Status: {status}")
# Calling using keyword arguments out of sequence
create_user_profile(status="Active", role="Administrator", username="admin_nikita")
Output:
User: admin_nikita | Role: Administrator | Status: Active
Real-Time Example 2: Default Argument Values
Assign default fallback values to parameters so they become optional during function calls.
Python
def calculate_invoice_total(subtotal, tax_rate=0.05, shipping_fee=50):
total = subtotal + (subtotal * tax_rate) + shipping_fee
return round(total, 2)
# Using default tax and shipping
print("Invoice 1 Total: โน", calculate_invoice_total(1000))
# Overriding default shipping fee
print("Invoice 2 Total: โน", calculate_invoice_total(1000, shipping_fee=120))
Output:
Invoice 1 Total: โน 1100.0
Invoice 2 Total: โน 1170.0
Real-Time Example 3: Variable-Length Arguments (*args)
Use
*args to accept any number of positional arguments packed automatically into a tuple.
Python
def calculate_cart_total(*item_prices):
print(f"Received {len(item_prices)} items in cart.")
return sum(item_prices)
print("Total Cart 1: โน", calculate_cart_total(450, 1200, 300))
print("Total Cart 2: โน", calculate_cart_total(100, 250, 50, 80, 500))
Output:
Received 3 items in cart.
Total Cart 1: โน 1950
Received 5 items in cart.
Total Cart 2: โน 980
Real-Time Example 4: Variable-Length Keyword Arguments (**kwargs)
Use
**kwargs to accept any number of keyword arguments packed into a dictionary.
Python
def configure_server_settings(**settings):
print("Applying Server Configuration:")
for key, value in settings.items():
print(f" - {key}: {value}")
configure_server_settings(host="192.168.1.10", port=8080, ssl_enabled=True, timeout=30)
Output:
Applying Server Configuration:
- host: 192.168.1.10
- port: 8080
- ssl_enabled: True
- timeout: 30
Real-Time Example 5: Combining Standard Arguments, *args, and **kwargs
Maintain strict parameter order: standard parameters first, followed by
*args, and finally **kwargs.
Python
def generate_audit_report(report_name, *metrics, **metadata):
print(f"Report: {report_name}")
print("Recorded Metrics:", metrics)
print("Metadata Details:", metadata)
generate_audit_report("Q1 Financial Audit", 45000, 62000, 78000, author="Nikita", status="Verified")
Output:
Report: Q1 Financial Audit
Recorded Metrics: (45000, 62000, 78000)
Metadata Details: {'author': 'Nikita', 'status': 'Verified'}
Real-Time Example 6: Keyword-Only Arguments
Force certain parameters to be passed strictly as keyword arguments by placing an asterisk
* before them.
Python
def send_notification(message, *, recipient_email, priority="Normal"):
print(f"Sending message: '{message}' to {recipient_email} [Priority: {priority}]")
# Correct call using keyword arguments
send_notification("Server offline alert!", recipient_email="admin@infotech.com", priority="High")
# Calling send_notification("Alert!", "admin@infotech.com") would raise a TypeError!
Output:
Sending message: 'Server offline alert!' to admin@infotech.com [Priority: High]
Real-Time Example 8: Positional-Only Arguments
Force parameters to be passed strictly by position using a forward slash
/.
Python
def calculate_vector_magnitude(x, y, /):
return (x ** 2 + y ** 2) ** 0.5
# Must be passed positionally
print("Vector Magnitude:", calculate_vector_magnitude(3, 4))
# Calling calculate_vector_magnitude(x=3, y=4) would raise a TypeError!
Output:
Vector Magnitude: 5.0
Real-Time Example 9: Argument Unpacking with * and **
Unpack lists/tuples with
* and dictionaries with ** when passing them into functions.
Python
def register_employee(name, department, salary):
print(f"Employee: {name} | Dept: {department} | Salary: โน{salary}")
emp_list = ["Rahul Sharma", "Engineering", 75000]
emp_dict = {"name": "Priya Singh", "department": "HR", "salary": 65000}
# Unpacking list into positional arguments
register_employee(*emp_list)
# Unpacking dictionary into keyword arguments
register_employee(**emp_dict)
Output:
Employee: Rahul Sharma | Dept: Engineering | Salary: โน75000
Employee: Priya Singh | Dept: HR | Salary: โน65000
Real-Time Example 10: Mutable Default Arguments Trap
Avoid using mutable objects like lists as default arguments; use
None instead to prevent shared state bugs.
Python
# Safe approach using None for mutable default parameters
def add_audit_log(timestamp, log_list=None):
if log_list is None:
log_list = []
log_list.append(timestamp)
return log_list
print(add_audit_log("10:00 AM"))
print(add_audit_log("10:15 AM")) # Creates a fresh list correctly
Output:
['10:00 AM']
['10:15 AM']