Python tutorials > Core Python Fundamentals > Functions > What are function arguments?
What are function arguments?
Function arguments are the values passed to a function when it's called. They allow you to provide input to the function, enabling it to perform operations based on those inputs. Understanding function arguments is crucial for writing reusable and modular Python code.
Basic Argument Passing
This example demonstrates the most basic form of argument passing. The greet
function takes one argument, name
. When the function is called, the value provided in the parentheses is assigned to the name
parameter inside the function's scope. The function then uses this value to print a personalized greeting.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Passing 'Alice' as an argument
greet("Bob") # Passing 'Bob' as an argument
Positional Arguments
Positional arguments are passed to a function based on their order. In the describe_person
function, the first argument is assigned to name
, the second to age
, and the third to city
. The order in which you pass the arguments matters.
def describe_person(name, age, city):
print(f"Name: {name}, Age: {age}, City: {city}")
describe_person("Charlie", 30, "London")
Keyword Arguments
Keyword arguments are passed to a function using the parameter name followed by the value (parameter=value
). This allows you to pass arguments in any order, making your code more readable. If you use keyword arguments, you can reorder the parameters without affecting the function's behavior.
def describe_person(name, age, city):
print(f"Name: {name}, Age: {age}, City: {city}")
describe_person(name="Diana", age=25, city="Paris")
describe_person(age=40, name="Eve", city="New York") # Order doesn't matter
Default Arguments
Default arguments provide a default value for a parameter if no value is provided during the function call. In the greet
function, if no name
is given, it defaults to "Guest". Default arguments should always be defined after non-default arguments in the function definition.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Frank") # Output: Hello, Frank!
Variable-Length Arguments (*args)
The *args
syntax allows you to pass a variable number of positional arguments to a function. The arguments are collected into a tuple named args
within the function. This is useful when you don't know in advance how many arguments a function will need to receive. args
is just a name and the asterisk is what matters here.
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
print(add_numbers(1, 2, 3)) # Output: 6
print(add_numbers(1, 2, 3, 4, 5)) # Output: 15
Variable-Length Keyword Arguments (**kwargs)
The **kwargs
syntax allows you to pass a variable number of keyword arguments to a function. The arguments are collected into a dictionary named kwargs
within the function. This allows you to handle an arbitrary set of named parameters. Like with *args
, kwargs
is just a name and the double asterisk is what matters.
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name="Grace", age=35, city="Berlin")
Concepts behind the snippet
The core concepts behind function arguments are parameter passing, scope, and reusability. Arguments allow you to pass data into a function, making it flexible and reusable. The values of arguments are only accessible within the function's scope, preventing naming conflicts.
Real-Life Use Case Section
Imagine a function that calculates the area of a rectangle. You would pass the length and width as arguments. Or a function that formats a customer's address: you would pass the street, city, state, and zip code as arguments. Arguments are fundamental to making functions useful and adaptable to different situations.
Best Practices
Interview Tip
Be prepared to explain the difference between positional and keyword arguments. Also, understand how *args
and **kwargs
work and when they are useful. You might be asked to write a function that uses these features to handle a variable number of inputs.
When to use them
Use positional arguments when the order of the arguments is clear and consistent. Use keyword arguments when the order is not important or when you want to provide default values for some parameters. Use *args
and **kwargs
when you need to handle a variable number of inputs.
Memory footprint
Each argument passed to a function occupies memory. Passing large objects as arguments can increase the memory footprint of your program. Consider passing references to objects instead of copies to reduce memory usage when dealing with large datasets or complex objects. For immutable objects (like numbers and strings), this is less of a concern as they are often passed by value in practice, but the reference to that value takes up some memory.
Alternatives
Alternatives to using a large number of arguments include:
Pros
Cons
FAQ
-
What happens if I pass the wrong number of arguments?
Python will raise a
TypeError
. The error message will indicate the expected number of arguments and the number that were provided. -
Can I mix positional and keyword arguments?
Yes, you can, but positional arguments must come before keyword arguments in the function call.
-
How do I specify that a function should only accept keyword arguments?
You can use a
*
in the function definition to indicate that all subsequent arguments must be passed as keyword arguments. For example:def my_function(a, b, *, c, d): ...
. Here,c
andd
must be passed as keyword arguments (e.g.,my_function(1, 2, c=3, d=4)
).