Python中常用模块的使用

本文介绍了Python中的Keyword模块用于检查关键字,Random模块生成随机数,Turtle模块进行绘图,Math模块提供数学运算功能,以及Datetime和TimeCalender模块处理日期时间与日历。
摘要由CSDN通过智能技术生成

1.Keyword模块:提供了一个列表,其中包含Python中的所有关键字。你可以使用该模块来检查标识符是否是关键字。

import keyword
print(keyword.kwlist)

2.Random模块:用于生成各种类型的随机数。它提供了伪随机数生成器的功能,可以用于生成随机整数、随机浮点数、随机选择元素等。

#编写应用程序经常使用的随机模块
import random
print(random)
import random 
# 随机一个0-1之间的浮点数[0,1)
print(random.random())


#随机一个位于a,b之间的整数[a,b]
print(random.randint(1,3))

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


# 从列表中选择一个 指定每一个出现的权重,k=2代表选2次
print(random.choices(["哈尔滨","大连","长春"],[0.8, 0.15, 0.05], k=2))


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

3.Turtle模块:Python标准库中的一个绘图模块,用于绘制图形和动画。它提供了一组函数和方法,可以控制一个海龟图形的移动和绘制。

# 导入模块
import turtle
#print(turtle)

#乌龟坐标
turtle.goto(0,0)
#乌龟头方向
turtle.setheading(60)




# 指定画笔宽度
turtle.width(10)
# 指定画笔颜色
turtle.color("green", "blue")
turtle.fillcolor("blue")
# 开始填充
turtle.begin_fill()

# 画一个圆形
turtle.circle(100)

# turtle.forward(100)
# turtle.left(90)

#结束填充
turtle.end_fill()

#抬起画笔
turtle.up()

# 开始填充
turtle.begin_fill()
turtle.circle(10)
#turtle.forward(200)
#turtle.right(120)


#放下画笔
turtle.down()

turtle.forward(200)
turtle.right(120)
turtle.forward(200)
turtle.right(120)


#设置循环
turtle.mainloop()

4.Math模块:提供了数学运算相关的函数和常量。提供了许多数学相关的函数和常量。它包含了常见的数学运算函数,如三角函数、对数函数、幂函数等,以及一些常用的数学常量,如π和自然对数的底数e。

import math
# 无穷大
print(math.inf)
# 3.14
print(math.pi)

print(math.e)

# 弧度转角度
print(math.degrees(math.pi / 2))  # 90.0
# 角度转弧度
print(math.radians(60))
# 正弦值
print(math.sin(math.pi / 2))
# 反正弦值
print(math.asin(math.pi / 2))
# 余弦值
print(math.cos(math.pi / 2))
# 反余弦值
print(math.acos(math.pi / 2))
# 正切值
print(math.tan(math.pi / 2))
# 向上取整
print(math.ceil(3.14))  # 4
# 向下取整
print(math.floor(3.14))  # 3


# 对数 第一个是参数值 第二个是底数
print(math.log(1000, 10))  # 3.0

# 次方pow
print(math.pow(2, 3))   # 8.0
# 开根 sqr
print(math.sqrt(64))     # 8.0

5.Datetime模块:Python标准库中处理日期和时间的模块。它提供了各种类和函数,用于表示和操作日期、时间、时间间隔等。

# datetime 日期时间
from datetime import datetime
# 指定日期时间
# datetime0 = datetime(year=2001, month=5, day=25, hour=5, minute=29, second=11)
# 获取现在的日期时间
datetime0 = datetime.now()
print(type(datetime0))
print(datetime0.year, datetime0.month, datetime0.day, datetime0.hour, datetime0.minute, datetime0.second)
print(datetime0.strftime("%Y-%m-%d %H:%M:%S"))

6.TimeCalender模块:是与日历相关的若干函数和类,可以生成文本形式的日历。

# 日历
import calendar
# print(calendar)

# 年历
print(calendar.calendar(2024))
# 月历
print(calendar.month(2024, 1))
# 周几
print(calendar.weekday(2024, 1, 11))

#是否为闰年
print(calendar.isleap(2001))

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值