内容正文:
Python中常用模块
math、random
林城中学 陈 洁
2
# 定义fib函数,n为形参
def fib(n):
a, b = 1, 1
for i in range(3, n+1):
a, b = b, a+b
return b
# 输入月数
n = int(input('请输入第n个月:'))
# 调用fib函数,i值为实参
for i in range(1, n+1):
print(fib(i), end=' ')
int()
range()
input()
print()
回顾——斐波那契数列
3
def 函数1():
def 函数2():
def 函数3():
def 函数1():
def 函数2():
def 函数3():
1.py
2.py
3.py
my_function.py
my_function
新知——模块
4
模 块
模块是一个保存了Python代码的文件(.py)。
模块能定义函数,类和变量,也能包含可执行的代码。
我们编写的程序也是保存为.py文件的,它和模块文件有区别吗?
新知——模块
5
math
my_function
numpy
内置模块
自定义模块
第三方模块
在安装Python时一起被安装到系统中。如:math、random、time等。
用户根据需要,自己编写。
需要单独安装才可以使用。如:numpy、matplotlib等。
模块分类
log()
pow()
sin()
cos()
tan()
floor()
ceil()
import <模块> [as <别名>]
方式一:
>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> import math as m
>>> m.sqrt(2)
1.4142135623730951
from <模块> import <函数名>
方式二:
>>> from math import sqrt
>>> sqrt(2)
1.4142135623730951
>>> from math import *
>>> sqrt(2)
1.4142135623730951
sqrt()
math
模块导入
(导引P27)练习