Python Programming

Lecture 6 Functions, Modules

6.1 Functions Basics

Create functions

  • 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, follow 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.

  • 
    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

  • A fruitful function returns a value, while a void function performs an action but does not return a value.

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

  • Return means the termination of a function. If you have two returns, only the first one will take effect.


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


8

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

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

None

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'}

Exercise

“可乐瓶换饮料”问题

  • 小明喝可乐的习惯是: 每喝完一瓶,就可以用 3 个空瓶 换一瓶新的可乐。如果他一开始有 n 瓶可乐,请编写一个函数,计算他总共能喝到多少瓶可乐。
  • 提示思路:用 while 循环判断是否还能换,用整数除法 // 和取余 %

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 (当前工作目录).

  • PYTHONPATH (a list of directory names:标准库路径,第三方库路径)


import sys
print(sys.path)

Install third-party packages

  • Anaconda already includes many useful packages, and you can install additional ones as needed.
  • For Windows, open the anaconda prompt for anaconda, or open the cmd for original Python.

  • 
    
    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
    

Some third-party packages


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)
you-get安装使用说明

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