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.
  • The following function calls have the same output.


# A dog named Willie.
describe_pet('willie')
describe_pet(name='willie')

# A hamster named Harry.
describe_pet('harry', 'hamster')
describe_pet(name='harry', type='hamster')
describe_pet(type='hamster', name='harry')
  • 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'}

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)

Packages

  • Packages are namespaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.

  • Each package in Python is a directory which MUST contain a special file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.


mycompany
├─ __init__.py
├─ abc.py
└─ xyz.py
  • The name of modules are mycompany.abc and mycompany.xyz

  • Be careful! The name of modules you created should not be in conflict with the name of any system module, or any build-in function.

Third-party packages

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

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

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

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

  • 
    pip list
    #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