''' 【课程7.2】 模块创建及import指令运用 Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句 ''' # 创建一个模块,包含一个阶乘函数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,包括三个函数 # 模块路径问题 import pandas print(pandas.__file__) # 查看现有包所在路径,将自己创建的包存入改路径 import sys sys.path.append('C:/Users/Hjx/Desktop/') # 加载sys包,把新建的testmodel所在路径添加上 # 调用模块语句: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()调用模块函数(方法) # 简化模块名:import...as... import testmodel2 as tm2 print(tm2.f1(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)) # 单独导入模块的部分功能,但无法使用其他未导入模块功能 # 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)将一个列表内的元素打乱 # 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()
CH07模块与包
最新推荐文章于 2025-05-23 09:16:47 发布