2.8 KiB
2.8 KiB
Chapter 8. Functions
Passing an Arbitrary Number of Arguments
- Function uses
*arg_name
to collects arbitrary number of arguments. *
in parameter tells Python to make an empty tuple calledarg_name
and pack whatever values it receives into this tuple
NOTE: *args
is open used as generic parameter name
def make_pizza(*toppings):
"""Summarize the pizza we are about to make."""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
Mixing Positional and Arbitrary Arguments
- If function accept different kinds of arguments, Arbitrary Arguments must be placed at last.
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Using Arbitrary Keyword Arguments
- Function can use double asterisks
**
to cause Python to create an empty dictionary called user_info and pack whatever name-value pairs.
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
{'location': 'princeton', 'field': 'physics',
'first_name': 'albert', 'last_name': 'einstein'}
Storing Your Functions in Modules
Functions can be stored in different modules (python scripts) for better management.
Importing an Entire Module
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Importing Specific Functions
from module_name import function_name
Using as to Give a Function an Alias
from module_name import function_name as fn
Using as to Give a Module an Alias
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Importing All Functions in a Module
from module_name import *
Styling Functions
- Functions should have descriptive names, and function names should be lowercase letters and underscores.
- Every function should have a comment that explain concisely what the function does.
- If specify a default value, no space separation
def function_name(parameter_0, parameter_1='default value')
Generally follow PEP8