Function Arguments

basic
Published

December 27, 2024

Understanding how to use function arguments effectively is important for writing clean, reusable code. This post looks into the different types of function arguments, providing clear explanations and illustrative examples.

Positional Arguments

These are the simplest form of arguments. They are passed to a function in the order they are defined. The number of positional arguments passed must match the number of parameters defined in the function’s signature.

def greet(name, greeting):
  """Greets the user with a specified greeting."""
  print(f"{greeting}, {name}!")

greet("Alice", "Hello")  # Output: Hello, Alice!
greet("Bob", "Good morning") # Output: Good morning, Bob!

#greet("Charlie") 

Keyword Arguments

Keyword arguments allow you to specify the argument name when calling the function. This makes the code more readable and avoids the need to remember the exact order of arguments.

def describe_pet(animal_type, pet_name, age=None):
  """Displays information about a pet."""
  print(f"\nI have a {animal_type}.")
  print(f"My {animal_type}'s name is {pet_name.title()}.")
  if age:
    print(f"My {animal_type} is {age} years old.")

describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='willie', animal_type='dog', age=5)

Notice the use of age=None which provides a default value if the age is not specified.

Default Arguments

Default arguments provide a default value for a parameter if the caller doesn’t supply one. They improve code readability and flexibility.

def make_pizza(size, toppings='pepperoni'):
  """Makes a pizza with the specified size and toppings."""
  print(f"Making a {size}-inch pizza with {toppings}.")

make_pizza(16)  # Output: Making a 16-inch pizza with pepperoni.
make_pizza(12, 'mushrooms') # Output: Making a 12-inch pizza with mushrooms.

Arbitrary Positional Arguments (*args)

The *args syntax allows a function to accept any number of positional arguments. These arguments are collected into a tuple.

def make_sandwich(*ingredients):
    """Makes a sandwich with the given ingredients."""
    print("\nMaking a sandwich with:")
    for ingredient in ingredients:
        print(f"- {ingredient}")

make_sandwich('bread', 'cheese', 'tomato', 'lettuce')
make_sandwich('bread', 'ham')

Arbitrary Keyword Arguments (**kwargs)

Similarly, **kwargs allows a function to accept any number of keyword arguments. These arguments are collected into a dictionary.

def build_profile(first, last, **user_info):
  """Builds a dictionary containing everything we know about a user."""
  user_info['first_name'] = first
  user_info['last_name'] = last
  return user_info

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

Combining Argument Types

You can combine different argument types in a single function definition, but positional arguments must come before keyword arguments, and default arguments must follow non-default arguments. The order is: positional, default, *args, **kwargs.

def my_function(pos1, pos2, default_arg="default", *args, **kwargs):
  print(f"Positional 1: {pos1}")
  print(f"Positional 2: {pos2}")
  print(f"Default: {default_arg}")
  print(f"Arbitrary Positional: {args}")
  print(f"Arbitrary Keyword: {kwargs}")

my_function(1,2,third="3", fourth=4, fifth=5, sixth=6)