Jump to content

Functions and Modules: Difference between revisions

From Slow Like Wiki
Rob (talk | contribs)
Created page with " <syntaxhighlight lang="python" line> def make_shirt(size = "L", slogan = "I love Python"): # two params both with default values """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")..."
 
No edit summary
 
(6 intermediate revisions by one other user not shown)
Line 1: Line 1:
== Functions ==
Define and Call a Function:
<syntaxhighlight lang="python" line>
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
</syntaxhighlight>
Return a Dictionary from a Function:
<syntaxhighlight lang="python" line>
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
</syntaxhighlight>
Use while loop in function to work through list
<syntaxhighlight lang="python" line>
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)
</syntaxhighlight>
Arbitrary Number of Arguments
<syntaxhighlight lang="python" line>
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')
</syntaxhighlight>
Arbitrary Key-Value Arguments
<syntaxhighlight lang="python" line>
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)
</syntaxhighlight>
== Modules ==
Importing Modules
<syntaxhighlight lang="python" line>
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
</syntaxhighlight>
<syntaxhighlight lang="python" line>
<syntaxhighlight lang="python" line>
def make_shirt(size = "L", slogan = "I love Python"):                    # two params both with default values
  """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 like Python")                                    # call with slogan only (must specify param name)
make_shirt(size = "S", slogan = "I like Python")                        # call with both size and slogan
</syntaxhighlight>
</syntaxhighlight>
[[Category:Python]]

Latest revision as of 17:41, 16 February 2025

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