Function parameters & arguments in Python


Video Lesson:


Lesson Transcript:

So far, the functions we've created execute a fixed task without context / inputs. But most often we want our functions to produce different outcomes depending on the context behind the function call.

For example, it would be nice if say_hello() would print a personalized message such as "Hello humans" or "Hello cats" or "Hello dogs", depending on the audience instead of "Hello world" no matter what.


Function parameters:

Function parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.

When a function is defined, its parameters are specified between the parentheses that follow the function name.

Here is our function with one parameter, audience:

def say_hello(audience):
	print("Hello " + audience)

Calling with arguments:

Then we can call say_hello and specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments.

# Function declaration:
def say_hello(audience):
	print("Hello " + audience)

# Function call:
say_hello("humans") # Output: Hello humans

We have passed one string argument: "humans". Inside the function audience will equal string "humans" and acts just like a regular variable.


Multiple parameters:

A function can take as many parameters as it needs. Here is a function with two parameters:

def printPerson(name, age):
	print(name + ", aged " + str(age))

# Let's call it:
printPerson("John", 30) # Output: John, aged 30
printPerson("Mary", 26) # Output: Mary, aged 26

Notice that the order in which arguments are passed and assigned follows the order that the parameters are declared.


Variables as arguments:

Variables can also be passed as arguments for function calls:

def printPerson(name, age):
	print(name + ", aged " + str(age))

name = "Andy"
age = 28

printPerson(name, age) # Output: Andy, aged 28

printPerson("Mary", age) # Output: Mary, aged 28

Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore the concept of function parameters and arguments in Python. Understanding how to use parameters and arguments is crucial for writing flexible and reusable code. Functions that accept parameters can perform tasks based on the input provided, making them more versatile and powerful.

Understanding the Basics

Function parameters are placeholders for the values that will be passed to the function when it is called. These values are known as arguments. When defining a function, you specify its parameters within the parentheses following the function name. When calling the function, you provide the arguments within the parentheses.

For example, consider the function say_hello(audience). Here, audience is a parameter. When we call say_hello("humans"), the string "humans" is the argument passed to the function.

Main Concepts

Let's delve deeper into the key concepts of function parameters and arguments:

Examples and Use Cases

Here are some examples to illustrate the use of function parameters and arguments:

# Example 1: Single Parameter
def greet(name):
    print("Hello, " + name)

greet("Alice")  # Output: Hello, Alice
greet("Bob")    # Output: Hello, Bob

# Example 2: Multiple Parameters
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

# Example 3: Variables as Arguments
def multiply(x, y):
    return x * y

num1 = 4
num2 = 7
product = multiply(num1, num2)
print(product)  # Output: 28

Common Pitfalls and Best Practices

When working with function parameters and arguments, be mindful of the following:

Advanced Techniques

Advanced techniques include using keyword arguments, variable-length arguments, and unpacking arguments. These techniques provide additional flexibility and functionality.

# Keyword Arguments
def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type} named {pet_name}.")

describe_pet(animal_type="dog", pet_name="Rex")

# Variable-Length Arguments
def sum_all(*numbers):
    return sum(numbers)

total = sum_all(1, 2, 3, 4, 5)
print(total)  # Output: 15

# Unpacking Arguments
def show_info(name, age):
    print(f"Name: {name}, Age: {age}")

person_info = ("Alice", 30)
show_info(*person_info)

Code Implementation

Let's implement a function that demonstrates the use of multiple parameters and keyword arguments:

# Function with multiple parameters and keyword arguments
def create_profile(first_name, last_name, age=None, city="Unknown"):
    profile = {
        "first_name": first_name,
        "last_name": last_name,
        "age": age,
        "city": city
    }
    return profile

# Creating profiles
profile1 = create_profile("John", "Doe", age=28, city="New York")
profile2 = create_profile("Jane", "Smith")

print(profile1)
print(profile2)

Debugging and Testing

When debugging functions, use print statements to check the values of parameters and arguments. Writing tests for functions ensures they work as expected. Here are some tips:

# Example of a simple test
def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

test_add()
print("All tests passed!")

Thinking and Problem-Solving Tips

When solving problems related to function parameters and arguments, consider the following strategies:

Conclusion

In this lesson, we covered the importance of function parameters and arguments in Python. We explored how to define functions with parameters, call them with arguments, and use advanced techniques. Mastering these concepts will help you write more flexible and reusable code.

Practice writing functions with different parameters and arguments to reinforce your understanding. Experiment with keyword arguments, variable-length arguments, and unpacking to gain confidence in using these techniques.

Additional Resources

For further reading and practice, check out the following resources: