Advanced Python - 2. Advanced Functions
2.4 Passing an Arbitrary Number of Arguments
2. Advanced Functions
2.1 Review of Basic Functions
- Python offers several advanced ways to define and call functions, giving you much more flexibility in how your functions handle input.
- As we know, a function takes an input, processes it according to a defined rule, and produces an output.
- From our introduction to function, we should be able to follow the example:
def first_function(x, y):
return x+(2*y)
print( first_function(7, 3) )
OUTPUT: 13
- In the example, x and y are our parameters with 7 and 3 being the arguments. The order of each of them matters so that x becomes 7 and y becomes 3. Values matched up this way are called positional arguments.
2.2 Keyword Arguments
- A keyword argument is a name-value pair that you pass to a function. These allow you to ignore the order. We can rewrite the above example as the following with the same result:
def first_function(x, y):
return x+(2*y)
print( first_function(y = 3, x = 7) )
OUTPUT: 13
2.3 Default Values
- When writing a function, you can define a default value for each parameter. If an argument for a parameter is provided in the function call, the argument will be used. If not, the default value will be used.
- Example:
def describe_pet(pet_name, animal_type='dog'):
print("I have a " + animal_type + ".")
print("Its name is " + pet_name + ".")
describe_pet('Jacko')
OUTPUT: I have a dog.
Its name is Jacko.
When the function is called with no animal_type specified, the value dog will be used by default as the argument. If we wanted a different animal_type, we could call the function with a second argument:
def describe_pet(pet_name, animal_type='dog'):
print("I have a " + animal_type + ".")
print("Its name is " + pet_name + ".")
describe_pet('Booboo', 'cat')
OUTPUT: I have a cat.
Its name is Booboo.
- When you use default values, any parameter with a default value needs to be listed after all of the parameters that don’t have default values.
2.4 Passing an Arbitrary Number of Arguments
- Arbitrary means “unspecified value”
- Sometimes we won’t know ahead of time how many arguments a function needs to accept. We can handle this.
Example:
- This example builds a pizza by accepting a number of toppings, but we never know how many toppings will be ordered. The following function has one parameter called *toppings which collects as many arguments as we provide.
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
OUTPUT: (‘pepperoni’)
(‘mushrooms’, ‘green peppers’, ‘extra cheese’)
- The asterisk in the parameter name *toppings tells Python to make an empty tuple called toppings and put whatever values it receives into this tuple.
2.5 Passing Keyword Arguments
- Sometimes a function will want to accept an arbitrary number of arguments, but you won’t know what kind of information it is. In this case, you can have the function accept as many key-value pairs (from dictionaries) as you provide.
Example:
- Here, we want to build a user profile. We know we will get the first and last name of the user, but we aren’t sure what other information we will receive.
def build_profile(first, last, **user_info):
# Build a dictionary containing what we know about a user
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location = 'princeton'
field = 'physics')
print(user_profile)
OUTPUT: {‘first_name’: ‘albert’, ‘last_name’: ‘einstein’, ‘location’: ‘princeton’,
‘field’: ‘physics’}
- The function would work no matter how many additional key-value pairs are provided in the function call.
Chapter 2 Assignments
A2.1 T-Shirt
Write a function called make_shirt() that accepts a size and the text of a message that should be printed on the shirt. The function should print a sentence summarizing the size of the shirt and the message printed on it.
- Call the function once using positional arguments to make a shirt.
- Call the function a second time using keyword arguments.
A2.2 Large Shirts
Modify the make_shirt() function from A2.1 so that shirts are large by default with a message that reads “I Love Python”. Make a large shirt and a medium shirt with the default message, and a shirt of any size with a different message.
A2.3 Sandwiches
Write a function that accepts a list of items a person wants on a sandwich. The function should have one parameter that collects as many items as the function call provides, and it should print a summary of the sandwich that is being ordered. Call the function three times, using a different number of arguments each time.
A2.4 Cars
Write a function that stores information about a car in a dictionary. The function should always receive a manufacturer and a model name. It should then accept an arbitrary number of keyword arguments. Call the function with the required information and two other name-value pairs, such as a color or an optional feature.
Your function should work for a call like this one:
car = make_car(‘subaru’, ‘outback’, color = ‘blue’, tow_package = True)
Print the dictionary that’s returned to make sure all the information was stored correctly.