What is a Positional Argument?
-
When you call a function, Python must match the argument in the function call with a parameter in the function definition. The simplest way to do this is based on the order of the arguments provided. Values matched this way are called positional arguments.
-
Example: Consider a function that displays information about website users. The following function tells us the userās email address and the userās last name.
python
1def user(emailAddress, lastName):
2 print("\nUser's Email Address: " + emailAddress)
3 print("User's Last Name: " + lastName.title())
4
5user("hbulldog@student.wcu.edu", "bulldog")Output:
1User's Email Address: hbulldog@student.wcu.edu
2User's Last Name: Bulldog- The function above shows that this function needs a userās email address and last name.
- When user() is called, we need to provide an email address and last name, in that order.
- In the function call, the argument āhbulldog@student.wcu.eduā is stored in the parameter emailAddress and the argument bulldog is stored in the lastName parameter.
What is a Keyword Argument?
- A keyword argument is a name-value pair that you pass to a function. You directly associate the name and the value within the argument.
- Example: Letās rewrite the above example code using keyword arguments to call user.
python
1def user(emailAddress, lastName):
2 print("\nUser's Email Address: " + emailAddress)
3 print("User's Last Name: " + lastName.title())
4
5user(emailAddress="hbulldog@student.wcu.edu", lastName="bulldog")- Note that the function user hasnāt changed. However, when we call the function, we explicitly tell Python which parameter each argument should be matched with.
Variable (Arbitrary) Keyword Arguments:
- A variable/arbitrary number of arguments allow you to place a special argument, usually called kwargs, with two asterisks before it.
- This will all you to write functions that accept as many key-value pairs as the calling statement provides. The function would look something like this:
python
1def user(emailAddress, **kwargs):
2 print("\nUser's Email Address: " + emailAddress)
3 print("User's First Name: " + kwargs["firstname"].title())
4
5user(emailAddress="hbulldog@student.wcu.edu",
6 lastName="bulldog",
7 firstname="harpua")- Note that we donāt have to use the double asterisks when weāre referring to kwargs inside the function.
- The definition of user() expects an email address, and then it allows the user to pass in as many name-value pairs as they want.
Output:
1User's Email Address: hbulldog@student.wcu.edu
2User's First Name: Harpua