Function Parameters#
The two birthday functions in the previous section were nearly identical. The only difference was the name. Parameters let us pass data into a function, eliminating duplication.
Defining a Parameter#
Add a parameter name inside the parentheses of the def line:
def happy_birthday(person):
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print(f"Happy Birthday, dear {person}.")
print("Happy Birthday to you!")
The parameter person is a local variable that receives a value when the
function is called.
Calling with an Argument#
When you call a function with a parameter, you supply an argument — the value to pass in:
>>> def happy_birthday(person):
... print("Happy Birthday to you!")
... print("Happy Birthday to you!")
... print(f"Happy Birthday, dear {person}.")
... print("Happy Birthday to you!")
...
>>> happy_birthday("Emily")
Happy Birthday to you!
Happy Birthday to you!
Happy Birthday, dear Emily.
Happy Birthday to you!
One function, but different results for different arguments. Edit the call to
happy_birthday("Andre") and run it again to see.
How it Works#
When Python sees happy_birthday("Emily"), it:
Creates a local variable
personinside the function.Assigns it the value
"Emily".Executes the body of the function.
Discards
personwhen the function finishes.
The next call happy_birthday("Andre") does the same thing with
"Andre".
Parameters vs. Arguments#
The terms parameter and argument are often used interchangeably, but technically:
A parameter is the name listed in the
defline:person.An argument is the value supplied in the call:
"Emily".