Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is an argument in Python

Understanding Arguments in Python

When you're starting to learn programming, it's like learning a new language. Just as you need to understand how sentences are formed in English or any other language, in programming, you need to understand how commands and functions work. One of the key components of these commands in Python is what we call "arguments". Let's break this down into simpler terms and explore what arguments are in the world of Python programming.

The Basics of Functions and Arguments

Imagine you're at a coffee shop. You tell the barista, "I'd like a coffee, please." But the barista needs more information to fulfill your request. What size? What kind? Any milk or sugar? In programming, when you ask Python to perform a function (just like asking the barista to make coffee), you often need to provide additional details. These details are known as arguments.

A function in Python is like a mini-program within your program. It's a block of code that performs a specific task. To make a function useful, you sometimes need to give it information to work with. This information is passed to the function through arguments.

Positional Arguments

Let's look at a simple function and its arguments. We'll define a function that tells us the area of a rectangle.

def calculate_area(length, width):
    area = length * width
    return area

In this function, length and width are arguments. They are called positional arguments because the position in which you pass the values matters. When you call the function, you need to keep the order the same.

rectangle_area = calculate_area(5, 3)
print(rectangle_area)  # This will print 15

Here, 5 is assigned to length and 3 to width because of their positions.

Keyword Arguments

What if you don't want to worry about the order of the arguments? That's where keyword arguments come into play. You can specify which value goes to which parameter by naming them during the function call.

rectangle_area = calculate_area(width=3, length=5)
print(rectangle_area)  # This will still print 15

Now, it doesn't matter which order we put the arguments in because we've specified their names.

Default Arguments

Sometimes, we want to have default values for arguments. For instance, if our coffee shop assumes that a coffee order is medium-sized unless otherwise specified, we can set up a default value for the size.

def order_coffee(type_of_coffee, size="medium"):
    print(f"Ordering a {size} {type_of_coffee}")

If you don't specify the size, it will automatically be "medium".

order_coffee("latte")  # This will print "Ordering a medium latte"

But if you want a different size, you can still specify it.

order_coffee("latte", "large")  # This will print "Ordering a large latte"

Variable-length Arguments

What if you want to order a coffee with an unpredictable number of extra options? Maybe you want caramel, whipped cream, and an extra shot of espresso. In Python, you can use variable-length arguments to handle this.

We use a special symbol * for an arbitrary number of positional arguments, often referred to as *args.

def order_coffee_with_extras(type_of_coffee, *extras):
    print(f"Ordering a {type_of_coffee} with {' '.join(extras)}")

order_coffee_with_extras("cappuccino", "caramel", "whipped cream", "extra shot")
# This will print "Ordering a cappuccino with caramel whipped cream extra shot"

Similarly, ** is used for an arbitrary number of keyword arguments, often referred to as **kwargs.

def order_coffee_with_details(type_of_coffee, **details):
    print(f"Ordering a {type_of_coffee}")
    for detail in details:
        print(f" - with {detail}: {details[detail]}")

order_coffee_with_details("espresso", sugar="less", milk="oat")
# This will print:
# Ordering an espresso
#  - with sugar: less
#  - with milk: oat

Combining Different Types of Arguments

In real-world scenarios, you'll often see functions that combine different types of arguments. The order in which you define them in your function is important:

  1. Positional arguments
  2. *args
  3. Keyword arguments
  4. **kwargs

Here's an example of a function that uses all of these:

def make_sandwich(bread, meat, *vegetables, sauce="mayo", **extra_spreads):
    sandwich = f"{meat} sandwich on {bread} bread with {', '.join(vegetables)}"
    sandwich += f" and {sauce}"
    for spread, amount in extra_spreads.items():
        sandwich += f" and {amount} of {spread}"
    return sandwich

print(make_sandwich("rye", "turkey", "lettuce", "tomato", sauce="mustard", avocado="a lot"))
# This will print:
# turkey sandwich on rye bread with lettuce, tomato and mustard and a lot of avocado

Intuitions and Analogies

To help understand arguments better, think of a function as a recipe. The arguments are the ingredients you need. Some ingredients (positional arguments) are essential and need to be added in a specific order. Others (keyword arguments) are optional or can be varied according to taste. Sometimes, you just throw in a handful of this or that (variable-length arguments), and other times, you have specific preferences for your ingredients (default arguments).

Conclusion

Arguments in Python are the way we provide information to functions so they can perform their tasks effectively. Just like in a conversation where you might provide details to make your meaning clear, in programming, you provide arguments to make your functions do exactly what you want. They are the bridge between generic operations and specific actions.

As you continue your Python journey, you'll find that understanding how to use arguments effectively will make your code more flexible and powerful. It's like learning to order the perfect coffee that suits your taste every time. So, go ahead and experiment with different types of arguments. Try writing your own functions and see how you can manipulate their behavior with the power of arguments. Happy coding!