Python 小栈_12:Python time与random等常用模块与包

今日所学:

一、module模块与包

1、一个.py文件就相当于一个模块
directory --->文件夹
package--->文件夹,其底下多了一个_init_文件
2、好处:大大提高代码的可维护性
3、三大模块:
(1)python标准库
(2)第三方模块
(3)应用程序自定义模块
4、import的作用:
(1)执行调用的模块文件
(2)引入变量名
import test
import sys
print(test.add(3,4))
print(sys.path)


>>>7

    5、几种书写

1、import test



2、from test import add
from test import sub 

from test import *  #*代表引入test中一切的函数,但不建议此法,因为你可能无法清楚地获得自己想要调用的函数

二、模块的导入方法

1、import导入

2、form my_module import cal

3、多层调用,用.隔开

from web.web1.web2.web3 import cal  --->支持调用,方式为cal.add
from web.web1.web2.web3.cal import add   --->支持调用,方式为add
from web.web1.web2 import web3   --->唯一不支持调用,默认执行web3下的_init_文件

4、注意:

(1)在使用import 调用时,解释器自己搜索路径的,倚靠import sys下的sys.path()来获取调用函数的位置,从而调用

(2)包只要被调用,就会执行内部的程序

(3)解释器只认path()给它提供的路径

(4)书写规范,也为了不让他人调用自己的文件,可在程序里面加入:if  __name__=="__main__"

三、time模块

1、时间戳、结构化时间(当地时间、国际标准化时间)

import time

print(time.time())  #时间戳,从1970年1月1日凌晨至今的秒数
print(time.localtime())  #结构化时间,指当地的时间(东八区)
print(time.gmtime())  #国际标准化的结构化时间,以英国的格林尼治为准
t=time.localtime()
print(t.tm_year)
print(t.tm_wday)

>>>
1584361990.0223598
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=16, tm_hour=20, tm_min=33, tm_sec=10, tm_wday=0, tm_yday=76, tm_isdst=0)
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=16, tm_hour=12, tm_min=33, tm_sec=10, tm_wday=0, tm_yday=76, tm_isdst=0)
2020
0

2、三者的转化

print(time.mktime(time.localtime()))  #把结构化时间转化为时间戳
print(time.strftime("%Y-%m-%d %X",time.localtime()))  #把结构化时间转化为字符串时间
print(time.strptime("2020:3:16:20:37:59","%Y:%m:%d:%X"))  #把字符串时间转化为结构化时间
print(time.asctime())  #默认将time.localtime()当做参数传入
print(time.ctime())   #默认将time.time()当做参数传入

>>>

1584362452.0
2020-03-16 20:40:52
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=16, tm_hour=20, tm_min=37, tm_sec=59, tm_wday=0, tm_yday=76, tm_isdst=-1)
Mon Mar 16 20:40:52 2020
Mon Mar 16 20:40:52 2020

四、random模块

1、random模块

import random
print(random.random())  #随机选取一个浮点数
print(random.randint(1,3))  #在【1,3】中取任意一个整型
print(random.randrange(1,3))  #在【1,3)中任意取一个整型
print(random.choice([1,2,3,4,5]))   #在列表中随意取一个值
print(random.sample([1,2,3,4,5],2))  #在列表中随意取两个值
print(random.uniform(1,4))  #取(1,4)中任意一个浮点数

item=[1,4,7,8]   #shuffle用来打乱item中的顺序
random.shuffle(item)
print(item)

>>>
0.8401350653632468
3
2
5
[2, 1]
3.7147723884913297
[8, 4, 1, 7]

2、写验证码

import random
def v_code():
    ret=""
    for i in range(5):  #验证码定5位
        num=random.randint(0,9)  #确认随机数字的范围
        alf=chr(random.randint(65,122))  #确认随机字母的范围,chr()是把数字对应的ascii表中的东西打印出来
        s=str(random.choice([num,alf]))  #在所有的随机数字和字母中随机选取组合
        ret+=s
    return ret
print(v_code())

>>>pT29w

以上。

猜你喜欢

转载自www.cnblogs.com/211293dlam/p/12506565.html