Jump to content

Functions and Modules

From Slow Like Wiki

Functions

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

Use while loop in function to work through list


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)

Arbitrary Number of Arguments


def make_pizza(size, *toppings):      # first value for size, any number for toppings
    """Print list of toppings """
    print(toppings)

make_pizza(8, 'mushrooms', 
    'ham', 'oregano', 'extra cheese')

Arbitrary Key-Value Arguments


def make_user(first, last, **user_info):       # two fixed params and then a dictionary called user_info
    """Create dictionary to store user info"""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

my_user = make_user('Thomas', 'Pynchon', 
    occupation = 'Writer', country = 'USA')

print(my_user)

Modules

Importing Modules


import authors             # get all functions in authors
import books as b          # get all functions from books with alias b 
from shops import *.       # get all functions from shops, no alias needed
from reader import create_reader

authors.create_author()    # call create_author() function from authors module
b.create_book()            # call function using module alias
create_shop()              # no module prefix if using *
create_reader()            # no module prefix if specific function import