Skip to main content

Defining Functions: `def` Keyword, Parameters, and Arguments

In our previous article, we introduced **[Introduction to Functions: The DRY principle and code reusability]**. We learned that functions are essential for writing clean, reusable, and maintainable code. This article dives deeper into the mechanics of creating functions, focusing on the def keyword and the crucial distinction between parameters and arguments.


📚 Prerequisites

To get the most out of this article, you should understand:

  • What a Python function is and why we use them.
  • Basic Python data types like strings and numbers.

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • The def Keyword: How to properly structure a function definition.
  • Parameters vs. Arguments: A clear explanation of the difference between these two fundamental terms.
  • Positional Arguments: How to pass arguments to a function based on their order.
  • Keyword Arguments: How to make your function calls more readable and flexible by naming your arguments.

🧠 Section 1: The Anatomy of a Function Definition

Let's revisit the basic structure of a Python function. Every function definition is a contract that specifies its name and the inputs it expects.

def function_name(parameter1, parameter2):
# The code to be executed is in this indented block
# ...
return "A value to send back"

The key components are:

  1. def Keyword: This is the starting signal. It tells Python, "Hey, I'm about to define a new function."
  2. function_name: A descriptive name that follows Python's snake_case convention. The name should clearly indicate what the function does (e.g., calculate_tax, send_email).
  3. Parentheses (): These are required. Inside them, you define the function's parameters.
  4. Parameters: These are the names you give to the inputs your function will receive. They act as local variables inside the function. A function can have zero or more parameters.
  5. Colon:: This marks the end of the function's header.
  6. Indented Body: The block of code that contains the function's logic. This is where the work gets done.
  7. return Statement (Optional): This statement exits the function and sends a value back to the caller.

💻 Section 2: Parameters vs. Arguments: A Critical Distinction

The terms "parameter" and "argument" are often used interchangeably, but they have distinct meanings. Understanding the difference is key to mastering functions.

  • A Parameter is the variable listed inside the parentheses in the function definition. It's a placeholder.
  • An Argument is the actual value that is sent to the function when it is called. It's the concrete data.

Think of it like a recipe:

  • The parameters are the ingredients listed in the recipe (e.g., "2 cups of flour," "1 cup of sugar").
  • The arguments are the actual ingredients you pull out of your pantry to use (the specific brand of flour, the specific type of sugar).

Let's see it in code:

# 'name' and 'location' are PARAMETERS
def generate_greeting(name, location):
print(f"Hello {name}, welcome to {location}!")

# "Alice" and "Python City" are ARGUMENTS
generate_greeting("Alice", "Python City")

In this example, when generate_greeting is called, the argument "Alice" is assigned to the parameter name, and the argument "Python City" is assigned to the parameter location.


🛠️ Section 3: Types of Arguments

Python is flexible in how you can pass arguments to functions. Let's explore the two most common types.

3.1 - Positional Arguments

This is the most straightforward way to pass arguments. The arguments are matched to the parameters based on their position (order). The first argument goes to the first parameter, the second to the second, and so on.

# positional_arguments.py

def create_user_profile(username, age, city):
"""Creates a user profile string."""
return f"User: {username}, Age: {age}, Location: {city}"

# The order of arguments must match the order of parameters
profile = create_user_profile("dev_dave", 35, "Codeville")
print(profile)
# Output: User: dev_dave, Age: 35, Location: Codeville

The Caveat: With positional arguments, the order is critical. If you mix them up, you can get logical errors that Python won't catch.

# Wrong order leads to a nonsensical result
wrong_profile = create_user_profile(35, "Codeville", "dev_dave")
print(wrong_profile)
# Output: User: 35, Age: Codeville, Location: dev_dave

3.2 - Keyword Arguments

To avoid the ambiguity of positional arguments, you can use keyword arguments. This is where you explicitly name each parameter when you pass its argument.

The syntax is parameter_name=value.

# keyword_arguments.py

def create_user_profile(username, age, city):
"""Creates a user profile string."""
return f"User: {username}, Age: {age}, Location: {city}"

# With keyword arguments, the order doesn't matter
profile1 = create_user_profile(username="dev_dave", age=35, city="Codeville")
profile2 = create_user_profile(city="Codeville", username="dev_dave", age=35)

print(profile1)
# Output: User: dev_dave, Age: 35, Location: Codeville
print(profile2)
# Output: User: dev_dave, Age: 35, Location: Codeville

Benefits of Keyword Arguments:

  • Readability: The function call becomes self-documenting. It's immediately clear which value is being assigned to which parameter.
  • Flexibility: You don't have to memorize the order of the parameters, which is especially helpful for functions with many inputs.

You can even mix positional and keyword arguments, but there's one rule: positional arguments must come before keyword arguments.

# Mixing positional and keyword arguments
# This works:
create_user_profile("dev_dave", city="Codeville", age=35)

# This will cause a SyntaxError:
# create_user_profile(username="dev_dave", 35, "Codeville")

✨ Conclusion & Key Takeaways

You've now taken a deeper look at the syntax and mechanics of defining Python functions. Mastering the use of parameters and the different argument-passing techniques is fundamental to writing robust and readable code.

Let's summarize the key takeaways:

  • def is for Definition: The def keyword is the entry point for creating any function.
  • Parameters are Placeholders, Arguments are Real: Parameters are defined in the function's signature, while arguments are the actual data you pass during a function call.
  • Order Matters for Positional Arguments: The default way of passing arguments relies on matching the order of arguments to the order of parameters.
  • Keyword Arguments Enhance Readability: By naming your arguments, you make your code clearer and less prone to errors from incorrect ordering.

Challenge Yourself: Write a function called describe_pet that takes two parameters: animal_type and pet_name. It should print a string like "I have a animal_type named pet_name." Call this function once using positional arguments and once using keyword arguments.


➡️ Next Steps

Now that you have a solid grasp of defining functions and passing arguments, we'll explore how to make functions even more powerful with the return statement. In the next article, we will focus on "Function Return Values: The return statement."

Happy coding, and keep building on your new skills!


Glossary (Python Terms)

  • Positional Argument: An argument that is assigned to a parameter based on its position in the function call.
  • Keyword Argument: An argument that is identified by the parameter name it is assigned to in the function call.
  • Function Definition: The block of code starting with def that creates a function, specifying its name, parameters, and logic.
  • Function Call: The act of executing a function by using its name and providing arguments.

Further Reading (Python Resources)