Parameters
Pass data into your functions
Functions are powerful. They let us reuse code. Parameters make functions even more flexible. They let us send information into our functions.
What are parameters?
Think of a function as a mini-program. Parameters are like the inputs for that mini-program. They are special variables. We define them when we create a function. They receive values when we call the function.
These values help the function do its job. We can make functions that act differently based on what we pass to them.
Basic parameters
Let's start with a simple example. We'll make a function that greets a person.
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")Here, name is the parameter. When we call greet("Alice"), the string "Alice" is passed to the name parameter. The function then prints "Hello, Alice!". The same happens for "Bob".
Multiple parameters
Functions can take more than one parameter. Just separate them with commas in the function definition.
def add_numbers(num1, num2):
total = num1 + num2
print(f"The sum is: {total}")
add_numbers(5, 3)
add_numbers(10, 20)In this example, num1 and num2 are both parameters. When you call add_numbers(5, 3), num1 becomes 5 and num2 becomes 3.
Default values
Sometimes a parameter often has the same value. We can give it a default value. This makes the parameter optional.
def greet_city(name, city="London"):
print(f"Hello, {name} from {city}!")
greet_city("Charlie")
greet_city("Diana", "Paris")In greet_city, city has a default value of "London". If you don't provide a city, it uses "London". If you do, it uses the value you provide.
Keyword arguments
You can pass arguments by their parameter name. These are called keyword arguments. This is helpful for clarity, especially with many parameters or default values.
def create_email(sender, receiver, subject="No subject"):
print(f"From: {sender}")
print(f"To: {receiver}")
print(f"Subject: {subject}")
create_email(receiver="eve@example.com", sender="frank@example.com")
create_email(receiver="grace@example.com", subject="Meeting", sender="henry@example.com")Notice how we explicitly name sender, receiver, and subject. The order doesn't matter for keyword arguments, only for positional arguments (the ones without the name).
Common mistakes
- Not passing enough arguments:
greet()will cause an error ifnameis required. - Passing too many arguments:
add_numbers(1, 2, 3)will fail ifadd_numbersonly expects two. - Getting the order wrong (for positional arguments): If
greet_city(city, name)was intended, callinggreet_city("Alice", "London")would mix them up.
Practice
Try these exercises to lock in what you just learned.
What's next?
You now know the basics of parameters. Try creating your own functions with different numbers of parameters, default values, and keyword arguments. Experiment and see what happens!
Next, you might explore return values. Functions can also send data back out into your program.