What are Function Arguments in Python?

Function arguments are the values passed to a function when it is called or invoked. They provide a way to communicate and transfer data between the code that calls the function and the code within the function itself. Think of function arguments as inputs that allow you to customize the behavior of a function and perform specific tasks based on the values provided. Let’s discover everything you need to know about function arguments!

Role of Arguments in Functions

Function arguments play a crucial role in defining the behavior and functionality of a function. They serve as placeholders for values that will be supplied when the function is called, enabling you to write reusable and flexible code. By accepting arguments, functions become more versatile and adaptable, allowing you to perform different operations with varying inputs.

Function Arguments Types

Python provides several types of function arguments, each serving a specific purpose and catering to different programming scenarios. Let’s explore the most commonly used types of function arguments in Python:

I. Positional Arguments: Basics and Usage

Positional arguments are the most fundamental type of function arguments. They are defined in the function declaration and matched with the arguments provided in the function call based on their position or order. When you call a function with positional arguments, Python assigns the values to the corresponding parameters in the order they appear.

Let’s consider a function called greet that takes two positional arguments: name and location. The function prints a personalized greeting message using the provided name and location.

Example Code
def greet(name, location): print(f"Hey {name}! Welcome to {location}.") greet("Alice", "New York")

In this example, we call the greet function with the arguments “Alice” and “New York“. The function receives these arguments and uses them to construct and print the greeting message:

Output
Hey Alice! Welcome to New York.

Expand your knowledge of Positional Arguments by delving into our dedicated article.

II. Default Arguments: Providing Default Values to Parameters

Default arguments allow you to assign default values to parameters in a function declaration. If an argument is not provided when calling the function, the default value is used instead. This provides a convenient way to make certain parameters optional, as they will take on a predefined value if no argument is passed.

Let’s consider a function called calculate_discount that calculates the discounted price of a product based on the original price and a discount percentage. The discount percentage is an optional argument, with a default value of 10%.

Example Code
def calculate_discount(price, discount_percentage=10): discount = price * (discount_percentage / 100) discounted_price = price - discount return discounted_price final_price = calculate_discount(100) print(f"The final price is: {final_price}")

In this example, we call the calculate_discount function with only the price argument, omitting the discount_percentage argument. Since we didn’t provide a value for discount_percentage, the function uses the default value of 10%. As a result, the discounted price is calculated based on the original price and the default discount percentage.

Output
The final price is: 90.0

III. Keyword Arguments: Specifying Arguments by Name

Keyword arguments allow you to pass arguments to a function using their parameter names, rather than relying on their position. This provides more flexibility and readability when calling functions, as you explicitly specify which argument corresponds to each parameter.

Consider a function called add_numbers that takes two numbers, a and b, and returns their sum. By using keyword arguments, we can specify the values for a and b explicitly in the function call.

Example Code
def add_numbers(a, b): return a + b result = add_numbers(a=5, b=3) print(f"The result is: {result}")

In this example, we call the add_numbers function and provide the values for a and b using keyword arguments. This approach enhances code readability, especially when dealing with functions that have multiple parameters.

Output
The result is: 8

IV. Variable-Length Arguments: Handling Arbitrary Number of Arguments

Sometimes, you may encounter situations where you need to handle a varying number of arguments in a function. Python allows you to define functions with variable-length arguments using the *args syntax. This enables your function to accept any number of arguments, which are then treated as a tuple within the function’s code.

Let’s consider a function called calculate_average that calculates the average of an arbitrary number of values.

Example Code
def calculate_average(*args): total = sum(args) average = total / len(args) return average result = calculate_average(4, 6, 8, 10) print(f"The average is: {result}")

In this example, we define the calculate_average function with the *args parameter. This parameter allows us to pass any number of arguments to the function. Within the function, we treat args as a tuple and perform the necessary calculations to determine the average.

Output
The average is: 7.0

V. Keyword-Only Arguments: Restricting Arguments to Keyword Syntax

Python also provides the option to define keyword-only arguments, which can only be passed using the keyword syntax and not as positional arguments. This allows you to enforce a specific calling convention and ensure that certain arguments are always specified by name.

Consider a function called send_email that sends an email to a recipient. The function accepts the recipient’s email address as a required positional argument and a keyword-only argument subject for specifying the email subject.

Example Code
def send_email(to, *, subject): print(f"Sending email to: {to}") print(f"Subject: {subject}") send_email("[email protected]", subject="Hello from Python Helper!")

In this example, we call the send_email function with the to argument as a positional argument and the subject argument as a keyword argument. The use of * before subject in the function declaration indicates that it can only be passed using the keyword syntax.

Output
Sending email to: [email protected]
Subject: Hello from Python Helper!

VI. Mixing Different Types of Arguments

In Python, you have the flexibility to mix different types of arguments in function declarations. By combining positional arguments, default arguments, keyword arguments, variable-length arguments, and keyword-only arguments, you can create highly customizable and versatile functions that suit your specific needs. Let’s explore how you can leverage this flexibility and create functions with mixed argument types.

When defining a function, you can include different types of arguments in the parameter list. For example, you can have positional arguments followed by default arguments, keyword arguments, and even variable-length arguments. This allows you to provide a wide range of options for users to call your function with different argument combinations.

Consider the following example:

Example Code
def greet(name, greeting="Hello", *args, **kwargs): print(f"{greeting}, {name}!") for arg in args: print(arg) for key, value in kwargs.items(): print(f"{key}: {value}") greet("Alice", "Hi", "Nice to meet you!", location="New York", profession="Software Engineer")

In this example, the greet function accepts a positional argument name, a default argument greeting with a default value of “Hello”, variable-length arguments args (collected as a tuple), and keyword arguments kwargs (collected as a dictionary). By mixing these different argument types, we can provide a personalized greeting while also allowing the user to pass additional arguments and keyword arguments.

Output
Hi, Alice!
Nice to meet you!
location: New York
profession: Software Engineer

The Order of Arguments

When a function is called with a mix of different argument types, it’s essential to understand how Python resolves and assigns values to the corresponding parameters. The order of the arguments plays a crucial role in determining how the arguments are matched with the parameters in the function declaration.

The order of argument resolution is as follows:

  1. Positional arguments: Python assigns values to the parameters based on their order in the function call. Positional arguments are matched from left to right.
  2. Keyword arguments: Python matches keyword arguments with the corresponding parameter names in the function declaration, regardless of their position.
  3. Default arguments: If any parameters still lack values, Python assigns the default values specified in the function declaration.

Let’s consider an example to illustrate the order of argument resolution:

Example Code
def example_function(a, b, c=0, d=0): print(f"a: {a}, b: {b}, c: {c}, d: {d}") example_function(1, 2, d=4, c=3)

In this example, we call the example_function with four arguments: 1, 2, c=3, and d=4. The positional arguments 1 and 2 are assigned to the parameters a and b based on their order. The keyword arguments c=3 and d=4 explicitly match the corresponding parameter names in the function declaration. As a result, all parameters receive the correct values, and the output reflects the assigned values for each parameter.

Output
a: 1, b: 2, c: 3, d: 4

Understanding the order of argument resolution ensures that you can call functions correctly and avoid any confusion or unexpected behavior when mixing different argument types.

Congratulations! You’ve now gained a comprehensive understanding of function arguments in Python, including mixing different types of arguments in function declarations, passing arguments to functions with examples and syntax, and understanding the order of argument resolution.

Whether you’re working with positional arguments, default arguments, keyword arguments, variable-length arguments, or keyword-only arguments, you can leverage their capabilities to write clean, efficient, and maintainable code.

So go ahead and apply your newfound knowledge of function arguments in your Python projects. Experiment with different argument types, mix and match them to suit your needs, and unleash the full potential of functions in your programming journey. Happy coding!

 
Scroll to Top