Python中常用模块的使用

一、Keyword

1、keyword.kwlist

获取 Python 中所有的关键字列表。

print(keyword.kwlist)

2、keyword.iskeyword

判断一个字符串是否为 Python 的关键字。如果是,则返回 True;否则返回 False。

print(keyword.iskeyword("for"))

二、Random

1、random.random

# 从[0,1)中随机一个小数
print(random.random())

2、random.randint

# 从[n,m]中选择一个整数
print(random.randint(1, 7))

3、random.choice

# 从列表中选1个
print(random.choice(["哈尔滨", "大连", "长春"]))

4、random.choices

# 从列表中选择n个,设置权重,choices k=2是选两次的意思,不是2个
print(random.choices(["哈尔滨", "大连", "长春"], [0.1, 0.2, 0.7], k=2))

5、random.sample

# 从列表中选择n个
print(random.sample(["哈尔滨", "大连", "长春"], k=2))
# print(random.sample(["", "", "", ……, ""],k = n))

三、Turtle

四、Math

# 正无穷大
a = math.inf
# 负无穷大
b = -math.inf

② 

# 复制后面的符号给前面的数
print(math.copysign(2, -6))

③ 

# 判断其中的内容是否是数字,若是数字返回False
print(math.isnan(math.pi))

④ 

# π
print(math.pi)
print(math.pi / 4)

⑤ 

# 弧度转角度
print(math.degrees(math.pi / 4))        # 45.0
# 角度转弧度
print(math.radians(180))                # 3.141592653589793

⑥ 

# 注意其中的内容是弧度
print(math.sin(math.pi))
print(math.cos(0))
print(math.tan(math.pi / 4))
# 注意其中的内容是值
print(math.degrees(math.asin(1)))

 ⑦

c = math.pi

# 向上取整
print(math.ceil(c))
# 向下取整
print(math.floor(c))

⑧ 

# 对数
# math.log(x, base) 函数可以计算以指定底数 base 对指定数 x 进行对数运算。
# 第一个参数是值,第二个参数是底数
print(math.log(1000, 10))       # 3
print(math.log2(1024))          # 10

⑨ 

# sqrt  开根
print(math.sqrt(64))            # 8

⑩ 

# pow 次方
print(math.pow(2, 4))           # 16.0

五、Datetime

六、Time

①睡眠,即等待时间

time.sleep(2)

② time.time()时间戳

# time.time()整数部分是从1970-1-1 0时到现在的秒数
# 也叫做时间戳
print(time.time())
# 1704937398.1666298

③ 获取当前时间

print(time.strftime("%Y/%m/%d %H:%M:%S"))
# 2024/01/11 09:47:12

④ 获取当地时间

print(time.localtime())
print(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))
print(time.strftime("%Y/%m/%d %H:%M:%S", (1999, 9, 9, 9, 9, 9, 0, 0, 0)))
# time.struct_time(tm_year=2024, tm_mon=1, tm_mday=11, tm_hour=9, tm_min=47, tm_sec=12, tm_wday=3, tm_yday=11, tm_isdst=0)
# 2024/01/11 09:47:12
# 1999/09/09 09:09:09

 ⑤获取星期、月份、几号、时间、年份

print(time.ctime())
# Thu Jan 11 09:47:12 2024

七、Calender

①年历

print(calendar.calendar(2024))

②月历

print(calendar.month(2024, 1))

③计算第周几,从0开始;传入年份、月份、日期

print(calendar.weekday(2024, 1, 11))
# 3

④是否是闰年

print(calendar.isleap(2024))
# True

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值