Function Parameters#
Note
Source: Adapted from the C# edition (functions/funcparam.rst).
The birthday-with-name example is a Python translation of the C#
original.
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:
happy_birthday("Emily")
print()
happy_birthday("Andre")
Output:
Happy Birthday to you!
Happy Birthday to you!
Happy Birthday, dear Emily.
Happy Birthday to you!
Happy Birthday to you!
Happy Birthday to you!
Happy Birthday, dear Andre.
Happy Birthday to you!
One function, two different results, because the argument differs.
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".