Python function arguments
In Python, function arguments are the inputs we provide to a function when we call it. Using arguments makes our functions flexible and reusable, allowing them to handle different inputs without altering the code itself. Python offers several ways to use arguments, each designed for specific scenarios. Let's break it down clearly and simply.
def greet(name):
print(f"Hello, {name}!")
#GeeksforGeeks is the argument
greet("GeeksforGeeks")
Output
Hello, GeeksforGeeks!
Explanation:
- In this example, the function
greet
takes an argumentname
and uses it to print a personalized greeting. We can replace"GeeksforGeeks"
with any name, and the function will adapt.
Types of Arguments
1. Positional Arguments
Positional Arguments are the most common type of arguments. The values we pass are assigned to the function parameters in the same order they’re defined.
def describe_pet(name, species):
print(f"{name} is a {species}")
# "Buddy" → name, "dog" → species
describe_pet("Buddy", "dog")
Output
Buddy is a dog
- Key Point: The order matters. If we swap the arguments, the meaning changes.
2. Keyword Arguments
With keyword arguments, we specify which value goes to which parameter, making our code more readable and flexible. This way, we don’t have to worry about the order of the arguments.
def introduce(name, age, city):
# Introduces a person with their
#name, age, and city
print(f"My name is {name}, I am {age} years old, and I live in {city}.")
introduce(name="Alice", age=25, city="New York")
Output
My name is Alice, I am 25 years old, and I live in New York.
- Key Point: The order doesn’t matter when using keyword arguments.
3. Default Arguments
Default arguments are handy when we want to provide a default value for a parameter, in case the caller doesn’t specify one.
def greet(name="there"):
# Greets the user with a default value of "there"
#if no name is provided
print(f"Hello, {name}!")
greet()
greet("GeeksforGeeks")
Output
Hello, there! Hello, GeeksforGeeks!
- Key Point: weour can skip default arguments when calling the function, but we can still override them if needed.
Variable-Length Arguments
Sometimes, we don’t know how many arguments a function might need to handle. Python provides tools for this, namely *args and **kwargs:
1. *args
for Positional Arguments
Use *args
to accept any number of positional arguments. These are treated as a tuple inside the function.
def sum_numbers(*args):
# Prints the arguments and returns their sum
print(f"{args}")
return sum(args)
print(sum_numbers(1, 2, 3, 4))
Output
(1, 2, 3, 4) 10
**kwargs
for Keyword Arguments
Use **kwargs
to accept any number of keyword arguments. These are treated as a dictionary inside the function.
def print_details(**kwargs):
# Iterates over keyword arguments and prints each key-value pair
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name="Harshit", age=25, city="New Delhi")
Output
name: Harshit age: 25 city: New Delhi