Functions and Modules
Appearance
Define and Call a Function:
def make_shirt(size = "L", slogan = ""): # two params. One has a default value, other is optional
"""Generate a T-shirt order with size and slogan """ # for documentation of function purpose
print(f"\nYou ordered a T-shirt saying '{slogan}' in size {size}.\n")
make_shirt() # call with defaults
make_shirt("M") # call with size only
make_shirt(slogan = "I Love Python") # call with slogan only (must specify param name)
make_shirt(size = "S", slogan = "I Love Python") # call with both size and slogan
Return a Dictionary from a Function:
def person(first_name, last_name, age = None): # age is optional
"""Return names as dictionary"""
person = {'first_name': first_name, # create the dictionary
'last_name': last_name}
if age: # manage optional age
person['age'] = age
return person # return dictionary
writer = person('Thomas', 'Pynchon', 84) # call function
print(writer) # print returned dictionary
def publish(submissions, published):
""" Loop through submissions and move to published """
while submissions:
article = submissions.pop()
print(f"Publishing submission: {article}")
published.append(article)
show_publications(published)
def show_publications(published)
""" List published articles """
print("The following articles are published:")
for article in published:
print(article)
submissions = [
'Beginning Python',
'Intermediate Python',
'Advanced Python',
]
published = []
publish(submissions, published)
Pass an Arbitrary Number of Arguments
def make_pizza(*toppings):
"""Print list of toppings """
print(toppings)
make_pizza('mushrooms', 'ham', 'oregano', 'extra cheese')