Python Function Arguments

Now, if you’ve been coding for a while, you might already know that functions are like little tools that help us do stuff. They take some input (arguments) and give us an output based on those inputs. But what makes Python so awesome is that it allows us to pass arguments in all sorts of ways!

First up, we have the classic positional argument. This is where you just write out the name of the function followed by a list of values inside parentheses:

# This function takes in two arguments, x and y, and returns the sum of the two numbers.
def add_numbers(x, y):
    return x + y

# The result variable is assigned the value returned by the add_numbers function when called with the arguments 3 and 5.
result = add_numbers(3, 5) # returns 8

Pretty straightforward, right? But what if you want to pass in some arguments that don’t have a specific order or name? That’s where keyword arguments come in! These are like little labels for your input values:

# This function takes in two arguments, name and age, and prints out a statement using those values
def print_info(name, age):
    print("My name is {} and I am {} years old.".format(name, age))

# This line calls the print_info function and passes in the arguments age and name, using keyword arguments to specify the order
print_info(age=25, name="John Doe") # prints "My name is John Doe and I am 25 years old."

And if you want to pass in a bunch of arguments at once (like when you’re working with lists or dictionaries), that’s where the * and ** operators come in! These allow us to unpack our input values into separate variables:

# This function takes in a list of items and prints each item on a separate line
def print_list(items):
    for item in items:
        print(item)

# Create a list of numbers
my_list = [1, 2, 3]

# Call the print_list function and pass in the list using the * operator to unpack the list into separate arguments
print_list(*my_list) # prints "1", "2", and "3" on separate lines

# This function takes in keyword arguments and updates the dictionary with new key-value pairs
def update_dict(**kwargs):
    my_dict.update(kwargs)

# Create a dictionary with a key-value pair
my_dict = {"name": "John Doe"}

# Call the update_dict function and pass in keyword arguments using the ** operator to unpack the arguments into separate key-value pairs
update_dict(age=25, location="San Francisco") # updates the dictionary with new key-value pairs

And that’s it! With these tools in your toolbox, you can write functions that are flexible and easy to use. So go ahead and start experimenting who knows what kind of crazy stuff you might come up with?

SICORPS