【课程7.2】 模块创建及import指令运用
Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句
1.创建一个模块,包含一个阶乘函数f1(n)、一个列表删值函数f2(lst,x),一个等差数列求和函数f3(a,d,n)
def f1(n):
y = 1
for i in range(1,n+1):
y = y * i
return y
# 创建阶乘函数f1(n)
def f2(lst,x):
while x in lst:
lst.remove(x)
return lst
# 创建列表删值函数f2(lst,x)
def f3(a,d,n):
an = a
s = 0
for i in range(n-1):
an = an + d
s = s + an
return s
# 创建等差数列求和函数f3(a,d,n)
# 创建模块testmodel2,包括三个函数
2.模块路径问题
import pandas
print(pandas.__file__)
# 查看现有包所在路径,将自己创建的包存入改路径
import sys
sys.path.append('C:/Users/Hjx/Desktop/')
# 加载sys包,把新建的testmodel所在路径添加上
3.调用模块语句:import
import testmodel2
print(testmodel2.f1(5))
print(testmodel2.f2([2,3,4,5,5,5,6,6,4,4,4,4],4))
print(testmodel2.f3(10,2,10))
# 直接用import调用模块,.f1()调用模块函数(方法)
---------------------------------------------------------------------
120
[2, 3, 5, 5, 5, 6, 6]
180
4.简化模块名:import…as…
import testmodel2 as tm2
print(tm2.f1(5))
# 简化模块名
---------------------------------------------------------------------
5.调用部分模块语句:From…import 语句
from testmodel2 import f2
print(f2([2,3,4,5,5,5,6,6,4,4,4,4],4))
#print(f3(10,2,10))
# 单独导入模块的部分功能,但无法使用其他未导入模块功能
---------------------------------------------------------------------
6.python标准模块 —— random随机数
import random
x = random.random()
y = random.random()
print(x,y*10)
# random.random()随机生成一个[0:1)的随机数
m = random.randint(0,10)
print(m)
# random.randint()随机生成一个[0:10]的整数
st1 = random.choice(list(range(10)))
st2 = random.choice('abcdnehgjla')
print(st1,st2)
# random.choice()随机获取()中的一个元素,()种必须是一个有序类型
lst = list(range(20))
sli = random.sample(lst,5)
print(sli)
# random.sample(a,b)随机获取a中指定b长度的片段,不会改变原序列
lst = [1,3,5,7,9,11,13]
random.shuffle(lst)
print(lst)
# random.shuffle(list)将一个列表内的元素打乱
---------------------------------------------------------------------
0.44159988059787625 8.117099777940593
6
1 e
[16, 13, 7, 5, 6]
[9, 7, 3, 1, 13, 5, 11]
7.python标准模块 —— time时间模块
import time
for i in range(2):
print('hello')
time.sleep(1)
# time.sleep()程序休息()秒
print(time.ctime())
print(type(time.ctime()))
# 将当前时间转换为一个字符串
print(time.localtime())
print(type(time.localtime()))
# 将当前时间转为当前时区的struct_time
# wday 0-6表示周日到周六
# ydat 1-366 一年中的第几天
# isdst 是否为夏令时,默认为-1
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
# time.strftime(a,b)
# a为格式化字符串格式
# b为时间戳,一般用localtime()
---------------------------------------------------------------------
hello
hello
Fri Dec 15 17:17:47 2017
<class 'str'>
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=15, tm_hour=17, tm_min=17, tm_sec=47, tm_wday=4, tm_yday=349, tm_isdst=0)
<class 'time.struct_time'>
2017-12-15 17:17:47
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身