Python Programming

Lecture 6 Functions, Modules

6.1 Functions Basics

  • A function is a named sequence of statements that performs a computation.

  • Build-in Functions

    int(), float(), str(), type() and etc.

  • To make your own functions, two steps: 1. define a function 2. call a function

  • 
    def lyrics():
        print("I'm okay.")
    
    lyrics()
    
  • The first line of the function is called the header. The rest is called the body. You can use it inside another function

  • 
    def repeat_lyrics():
        lyrics()
        lyrics()
    
    repeat_lyrics()
    
    
    I'm okay.
    I'm okay.
    

Parameters and arguments (形参和实参)


def print_twice(bruce): 
    print(bruce)
    print(bruce)

print_twice('Spam')
print_twice(17)

Spam
Spam
17
17

michael = 'Eric, the half a bee.'
print_twice(michael)

Eric, the half a bee.
Eric, the half a bee.

Multiple parameters

  • Positional Arguments


def describe_pet(type, name):
    print(f"My {type}'s name is {name}.")

describe_pet('hamster', 'Harry')
describe_pet('dog', 'Willie')

My hamster's name is Harry.
My dog's name is Willie.

describe_pet('harry', 'Hamster') #Order Matters

My harry's name is Hamster.
  • Keyword Arguments


def describe_pet(type, name):
    print(f"My {type}'s name is {name}.")

describe_pet(type='hamster', name='harry')
describe_pet(name='harry', type='hamster')
  • Default Values


def describe_pet(name, type='dog'): 
    print(f"My {type}'s name is {name}.")

describe_pet(name='willie')




My dog's name is Willie.

describe_pet(name='harry', type='hamster') 
#The default value has been ignored.
  • Example: Making an Argument Optional


def show_name(first, middle, last):
    full_name=first+' '+middle+' '+last
    print(full_name.title())
show_name('john','lee','hooker')

def show_name(first, last, middle=''):
    if middle:
        full_name=first+' '+middle+' '+last
    else:
        full_name=first+' '+last
    print(full_name.title())
show_name('jimi', 'hendrix')

Fruitful functions and void functions

  • Some of the functions yield results, fruitful fucntions

    Some of the functions do not return a value, void fucntions

  • To return a result from a function, we use the return statement in our function.

  • 
    def addtwo(a, b):
        added = a + b
        return added 
    # if only return, then it will return None.
    
    x = addtwo(3, 5)
    print(x)
    
    
    def addtwo(a, b):
        added = a + b 
    
    x = addtwo(3, 5)
    print(x)
    
    
    None
    
  • Return means the termination of a function. If you have two returns, only the first one will take effect.

  • Return and Print


def addtwo(a, b):
    added = a + b 
    print(added)

x = addtwo(3, 5)
print(x)

8
None

def addtwo(a, b):
    added = a + b 
    print(added)
    return added

x = addtwo(3, 5)
print(x)

8
8
  • If we want to return multiple values, the function returns a tuple.


def addtwo(a, b):
    added = a + b
    return a, b, added

x = addtwo(3, 5)
print(x)

(3, 5, 8)
  • A function can return any kind of value you need it to, including more complicated data structures like lists and dictionaries.


def build_person(first, last):
    person = {1: first, 2: last}
    return person

musician = build_person('jimi', 'hendrix')
print(musician)

{1: 'jimi', 2: 'hendrix'}

Example: Improve the game in Lecture 2!


game_t = [[], ['a','b','c'], ['d','e'], ['x','y','z']]
game_m = [[], [0,2,0], [0,3,0], [0,0,0]]

def game(story, goto):
    for sentence in story:
        print(sentence)
        input()
    select = int(input("Please select? "))
    if select == 1:
        next_stage = goto[0]
    elif select == 2:
        next_stage = goto[1]
    elif select == 3:
        next_stage = goto[2]
    return next_stage

def start(t, m):
    x = 1
    while x!= 0:
        x = game(t[x], m[x])
    print("Game over")

start(game_t, game_m)

6.2 Modules

  • Module is a Python file, followed with .py

  • Storing Your Functions in Modules

  • 
    def make_pizza(size):
        print(f"Making a {size}-inch pizza")
    
  • It is saved as "pizza.py" file.

  • We make a separate file called making_pizzas.py in the same directory as pizza.py.

  • 
    import pizza
    
    pizza.make_pizza(16)
    

Importing Specific Functions


#from module_name import function_name
#from module_name import function_0, function_1, function_2

from pizza import make_pizza

make_pizza(16)

Using as to Give a Function an Alias


from pizza import make_pizza as mp

mp(16)

Using as to Give a Module an Alias


import pizza as p

p.make_pizza(16)
  • Importing All Functions in a Module


from pizza import *

make_pizza(16)
  • The asterisk in the import statement tells Python to copy every function from the module pizza into this program file. Because every function is imported, you can call each function by name without using the dot notation.

  • However, it's best not to use this approach when you're working with larger modules that you didn't write: if the module has a function name that matches an existing name in your project, you can get some unexpected results.

Search for Modules

  • When a module named is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named xxx.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).

  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

  • The installation-dependent default.


import sys
print(sys.path)

Third-party packages

  • Anaconda has already installed many useful packages.
  • 
    import requests
    print(dir(requests))
    
  • For win, open the anaconda prompt.

  • 
    
    pip install pillow
    #or conda install pillow
    
  • For macOS, open the terminal.

  • 
    pip install pillow
    #or conda install pillow
    
  • Uninstall the package

  • 
    pip uninstall pillow
    #or conda uninstall pillow
    
  • List all the packages

  • 
    pip list
    #or conda list
    

Example 1: math and random package


import math
print(dir(math))

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 
'acosh', 'asin','asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 
'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 
'inf', 'isclose', 'isfinite', 'isinf','isnan', 'isqrt', 'lcm', 'ldexp', 
'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter','perm', 
'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 
'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

import math

print(math.pi)
print(math.exp(50))
print(math.sin(math.pi/2))
print(math.acos(0.5))
print(math.log(5, 20))

import random

print(random.randint(1, 10))         # 产生 1 到 10 的一个整数型随机数
print(random.random())               # 产生 0 到 1 之间的随机浮点数
print(random.uniform(1.1, 5.4))      # 产生  1.1 到 5.4 之间的随机浮点数
print(random.choice('tomorrow'))     # 从序列中随机选取一个元素
print(random.randrange(1, 100, 2))   # 生成从1到100的间隔为2的随机整数
a = [1, 3, 5, 6, 7]                
random.shuffle(a)                    # 将序列a中的元素顺序打乱
print(a)
print(random.sample(a, 2))

Example 2: Third-party package


pip install you-get 
# youtube-dl
Free Python Games

pip install freegames

Summary

  • Functions
    • Reading: Python for Everybody, Chapter 4
    • Reading: Python Crash Course, Chapter 8