Python functions can accept arguments to provide input values. These arguments can be passed as positional arguments, keyword arguments, or default arguments. Understanding these argument types is essential for writing flexible and clear functions. This article explains each type with examples.
Positional arguments are passed to a function in the same order as the function's parameter list. The order is crucial when using positional arguments.
The following example demonstrates a function that takes two positional arguments:
# Function with positional arguments def greet(name, age): print(f"Hello, {name}! You are {age} years old.") # Calling the function with positional arguments greet("Alice", 25)
Output:
Hello, Alice! You are 25 years old.
Keyword arguments are explicitly assigned to a specific parameter in the function call. This makes the order of arguments irrelevant and improves code readability.
The following example uses keyword arguments to call a function:
# Function with keyword arguments def greet(name, age): print(f"Hello, {name}! You are {age} years old.") # Calling the function with keyword arguments greet(age=30, name="Bob")
Output:
Hello, Bob! You are 30 years old.
Default arguments are used when a parameter has a predefined value. If no argument is provided for that parameter, the default value is used.
The following example demonstrates a function with a default argument:
# Function with default arguments def greet(name, age=18): print(f"Hello, {name}! You are {age} years old.") # Calling the function with and without the default argument greet("Charlie", 22) # Override default greet("Diana") # Use default
Output:
Hello, Charlie! You are 22 years old. Hello, Diana! You are 18 years old.
You can combine different types of arguments in a function. When doing so, positional arguments must come before keyword arguments.
The following example combines all three types of arguments:
# Function combining all argument types def greet(name, age=18, city="Unknown"): print(f"Hello, {name}! You are {age} years old and live in {city}.") # Calling the function with various combinations greet("Eve", 25, "New York") # Positional arguments greet("Frank", city="Los Angeles") # Mix of positional and keyword greet(name="Grace") # Default arguments
Output:
Hello, Eve! You are 25 years old and live in New York. Hello, Frank! You are 18 years old and live in Los Angeles. Hello, Grace! You are 18 years old and live in Unknown.
Understanding positional, keyword, and default arguments allows you to write flexible and user-friendly functions in Python. Use positional arguments for required inputs, keyword arguments for readability, and default arguments to provide fallback values. Experiment with these examples to improve your function design skills.