目录
2.2.4random.randrange(start, stop[, step])
一、time库及其使用
1.1获取当前时间戳
time.time()返回自“新纪元”(1970年1月1日 00:00:00 UTC)以来的秒数,可以用于计算时间差等操作。
import time
timestamp = time.time()
print("当前时间戳:", timestamp)
1.2时间获取
1.3时间戳转换
time.localtime()将时间戳转换为当地时间,返回一个具有以下属性的time.struct_time对象:
- tm_year: 年份
- tm_mon: 月份
- tm_mday: 日
- tm_hour: 小时
- tm_min: 分钟
- tm_sec: 秒
- tm_wday: 周几,0为周一
- tm_yday: 当年的第几天
- tm_isdst: 是否为夏令时,1为是,0为否,-1为未知
import time
timestamp = time.time()
local_time = time.localtime(timestamp)
print("本地时间:", local_time)
日期转换为时间戳:
import time
date_str = "2021-03-26 17:50:13"
time_array = time.strptime(date_str, "%Y-%m-%d %H:%M:%S") # 将字符串转换为时间元组
timestamp = time.mktime(time_array) # 将时间元组转换为时间戳
print(timestamp)
1.4时间格式化输出
time.strftime()将time.struct_time对象格式化为字符串,常用的格式有:
- %Y: 年份,4位数字
- %m: 月份,2位数字
- %d: 日,2位数字
- %H: 小时,24小时制,2位数字
- %M: 分钟,2位数字
- %S: 秒,2位数字
import time
timestamp = time.time()
local_time = time.localtime(timestamp)
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print("格式化后的本地时间:", formatted_time)
strptime
下面的
date_string
是一个包含日期和时间的字符串,%Y-%m-%d %H:%M:%S
是一个日期格式化字符串,它指定了日期字符串的格式。strptime
函数会根据这个格式字符串,将date_string
解析成一个datetime
对象。上面的代码输出的结果为
2022-03-28 12:30:45
,它表示一个包含年、月、日、时、分、秒的日期时间对象。在格式化字符串中,
%Y
表示四位数的年份,比如2022
;%m
表示两位数的月份,比如03
;%d
表示两位数的日份,比如28
;%H
表示两位数的小时数,比如12
;%M
表示两位数的分钟数,比如30
;%S
表示两位数的秒数,比如45
。
import datetime
date_string = "2022-03-28 12:30:45"
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(date_object)
asctime
asctime
函数的参数是一个时间元组,该时间元组由time.localtime
函数返回。它返回一个可读性更好的时间字符串,其格式与ctime
函数返回的格式相同。
import time
# 获取当前时间的时间元组
current_time = time.localtime()
# 将时间元组格式化为可读性更好的时间字符串
time_str = time.asctime(current_time)
print(time_str)
4.延时操作
time.sleep()可以暂停程序的执行一段时间,单位是秒。
import time
print("开始倒计时...")
for i in range(10, 0, -1):
print(i)
time.sleep(1)
print("Boom!")
perf_counter()
perf_counter()
是 Python 中的一个计时器函数,用于精确地测量代码执行的时间。它返回一个表示当前时间的小数值,可以用于计算时间间隔。perf_counter()
函数与系统时钟的精度有关,通常比time()
函数更准确。在计算代码执行时间时,建议使用perf_counter()
函数。
import time
start_time = time.perf_counter()
# 执行需要计算时间的代码
for i in range(1000000):
x = i * 2
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print("代码执行时间为:", elapsed_time)
二、random库及其使用
2.1相关概念
2.2相关算法
2.2.1random()
生成一个0到1之间的随机浮点数
import random
x = random.random()
print(x)
2.2.2seed(a=None)
seed(a=None):初始化随机数生成器,如果a为None,则使用系统时间作为种子
import random
# 设置种子为1
random.seed(2)
# 生成随机整数
print(random.randint(0, 100))
# 再次生成随机整数
random.seed(3)
print(random.randint(0, 100))
其中
a
是整数类型的种子值。种子值是生成随机数的起点。如果使用相同的种子值,
random
模块将生成相同的随机数序列。因此,如果需要可重复的随机数序列,则应该在每次使用random
模块时设置相同的种子值。设置的seed()值仅一次有效
2.2.3randint(a, b):
生成一个a到b之间的随机整数,包括两个端点。如果a>b,则随机数范围为空,会抛出ValueError异常。
import random
for i in range(10):
print(random.randint(1, 100))
2.2.4random.randrange(start, stop[, step])
start
表示生成随机整数的起始范围(包含该数),stop
表示生成随机整数的结束范围(不包含该数),step
表示生成随机整数的步长,默认为1。
import random
# 生成1到10之间的随机整数
x = random.randrange(1, 11)
print(x)
2.2.5choice(seq)
import random
my_list = [1, 2, 3, 4, 5]
my_choice = random.choice(my_list)
print(my_choice) # 随机输出 my_list 中的一个元素
choice()
方法从my_list
中随机选择一个元素,并将其赋值给my_choice
变量,最后输出my_choice
的值。由于是随机选择,因此每次运行程序输出的结果可能会不同。
技巧生成一个随机的布尔值:
import random
b = random.choice([True, False])
2.2.6shuffle(seq)
seq
表示要打乱顺序的序列,可以是列表、元组或其他可变序列类型;random
表示可选参数,如果指定了random
参数,那么就会使用该参数作为随机数生成器,否则会使用默认的随机数生成器。
import random
# 定义一个列表
lst = [1, 2, 3, 4, 5]
# 打乱列表中元素的顺序
random.shuffle(lst)
# 输出打乱后的列表
print(lst)
用于打乱一个序列中元素的顺序。它的作用是将一个可变序列(例如列表)中的元素随机地重新排列,这样原序列中的元素顺序就被打乱了。使用
shuffle()
函数需要导入random
库。
2.2.7sample(seq, n)
random.sample(seq, n)
是 random
模块中的一个函数,用于从序列 seq
中随机选择 n
个元素,返回一个新的包含所选元素的列表。
如果 seq
包含重复元素,则 sample()
函数所返回的结果也可能包含重复元素。如果 n
大于 seq
的长度,则会引发 ValueError
异常。
import random
mylist = [1, 2, 3, 4, 5]
result = random.sample(mylist, 3)
print(result)
2.2.8uniform(a, b)
uniform(a, b)
是 random
库中的一个函数,用于生成一个指定区间 [a, b]
内的随机实数,其中 a
和 b
为区间的端点。生成的随机数的精度与 Python 浮点数的精度相同
import random
# 生成一个 [1, 10] 内的随机实数
x = random.uniform(1, 10)
print(x)
好玩的应用
import random
import string
# 定义密码长度和可选字符集合
password_length = 10
characters = string.ascii_letters + string.digits + "!@#$%^&*()"
# 生成密码
password = ''.join(random.choice(characters) for i in range(password_length))
password
三、turtle库及其使用
3.1概念
turtle库是Python的标准库之一,用于绘制图形和动画,非常适合初学者学习编程。turtle库提供了一些基本的绘图命令,如画线、画圆、填充等等,同时也支持键盘和鼠标事件,使得用户可以通过交互的方式控制图形的绘制。
3.2画布
画布(canvas)是一个很重要的概念。画布是指绘制图形的区域,可以理解为一张纸。在Turtle中,可以创建一个画布,指定它的大小和背景颜色,并在画布上绘制各种形状。
turtle为我们展开用于绘图区域,我们可以设置它的大小和初始位置
turtle.screensize(canvwidth=600,canvheight=800,bg='black')
#参数分别代表画布的宽、高、背景色
turtle.screensize()#返回默认大小(400,300)turtle.setup(width=0.6,height=0.6,startx=100,starty=100)
#输入宽和高为整数时, 表示像素; 为小数时, 表示占据电脑屏幕的比例
#(startx, starty): 这一坐标表示矩形窗口左上角顶点的位置, 如果为空,则窗口位于屏幕中心
import turtle
# 创建一个画布,并指定它的大小和背景颜色
canvas = turtle.Screen()
canvas.setup(width=800, height=600)
canvas.bgcolor('white')
# 在画布上绘制图形
turtle.penup()
turtle.goto(-100, 0)
turtle.pendown()
turtle.circle(50)
# 关闭画布
canvas.exitonclick()
3.3画笔
3.3.1画笔运动函数
1.setheading(angle)
:将画笔的朝向设置为指定角度
import turtle
t = turtle.Turtle()
t.setheading(90) # 将画笔的朝向设置为90度(正北方向)
2.circle(radius, extent=None, steps=None)
:绘制一个圆形
import turtle
t = turtle.Turtle()
t.circle(50) # 绘制半径为50的圆形
3.dot(size=None, *color)
import turtle
t = turtle.Turtle()
t.penup()
t.goto(-100, 100)
t.dot() # 默认画一个直径为1像素的黑色圆点
t.goto(0, 100)
t.dot(5, "red") # 画一个直径为5像素的红色圆点
t.goto(100, 100)
t.dot(10, "green") # 画一个直径为10像素的绿色圆点
t.goto(-100, 0)
t.dot(20, "blue") # 画一个直径为20像素的蓝色圆点
t.goto(0, 0)
t.dot(30, "orange") # 画一个直径为30像素的橙色圆点
t.goto(100, 0)
t.dot(40, "purple") # 画一个直径为40像素的紫色圆点
turtle.done()
4.speed(speed=None)
import turtle
t = turtle.Turtle()
t.speed(0) # 最快速度
for i in range(200):
t.forward(i)
t.right(91)
turtle.done()
5.goto(x, y)
:将画笔移动到指定的坐标位置
import turtle
t = turtle.Turtle()
t.goto(100, 100) # 移动到坐标(100, 100)的位置
6.penup
函数用于将画笔抬起,停止绘制
import turtle
t = turtle.Turtle()
t.penup()
t.goto(-100, 100)
t.pendown()
t.circle(50)
turtle.done()
7.pendown
函数用于将画笔放下,开始绘制
8.home
函数用于将画笔移动回原点(0,0)并重置其方向
import turtle
t = turtle.Turtle()
t.forward(100)
t.left(90)
t.forward(100)
t.home()
turtle.done()
3.3.2画笔控制函数
1.pensize
和pencolor
函数设置了画笔的线条宽度和颜色
import turtle
t = turtle.Turtle()
t.pensize(5)
t.pencolor('blue')
t.penup()
t.goto(-100, 0)
t.pendown()
for i in range(4):
t.forward(100)
t.right(90)
t.speed(1)
turtle.done()
2.fillcolor
函数用于设置填充颜色
import turtle
t = turtle.Turtle()
# 设置填充颜色为黄色
t.fillcolor('yellow')
# 开始填充
t.begin_fill()
# 绘制一个矩形
t.forward(200)
t.right(90)
t.forward(100)
t.right(90)
t.forward(200)
3.color(colorname) color(r, g, b)
参数
colorname
可以是字符串类型的颜色名或RGB颜色值,r
、g
、b
分别为红、绿、蓝三种颜色的数值,取值范围为0到255。
import turtle
t = turtle.Turtle()
# 设置画笔颜色为红色
t.color('red')
# 绘制一个矩形
t.forward(200)
t.right(90)
t.forward(100)
t.right(90)
t.forward(200)
t.right(90)
t.forward(100)
turtle.done()
4.filling
函数用于查询当前是否在填充状态,该函数没有参数,返回值为一个布尔值。
import turtle
t = turtle.Turtle()
# 开始填充
t.begin_fill()
# 查询当前是否在填充状态
if t.filling():
print('当前在填充状态')
else:
print('当前不在填充状态')
# 绘制一个矩形
t.forward(200)
t.right(90)
t.forward(100)
t.right(90)
t.forward(200)
t.right(90)
t.forward(100)
# 结束填充
t.end_fill()
# 查询当前是否在填充状态
if t.filling():
print('当前在填充状态')
else:
print('当前不在填充状态')
turtle.done()
5.hideturtle
函数用于隐藏画笔,该函数没有参数,没有返回值
import turtle
t = turtle.Turtle()
# 隐藏画笔
t.hideturtle()
# 绘制一个矩形
t.forward(200)
t.right(90)
t.forward(100)
t.right(90)
t.forward(200)
t.right(90)
t.forward(100)
turtle.done()
6.showturtle
函数用于显示画笔,该函数没有参数,没有返回值
import turtle
t = turtle.Turtle()
# 隐藏画笔
t.hideturtle()
# 显示画笔
t.showturtle()
# 绘制一个矩形
t.forward(200)
t.right(90)
t.forward(100)
t.right(90)
t.forward(200)
t.right(90)
t.forward(100)
turtle.done()
3.3.3全局控制函数
- turtle.title():用于设置窗口的标题,可以在窗口的标题栏中看到。
import turtle
turtle.title("Turtle Graphics")
turtle.done()
2.turtle.bgcolor():用于设置窗口的背景颜色。
import turtle
turtle.bgcolor("blue")
turtle.done()
3.turtle.setup():用于设置窗口的大小和位置
import turtle
turtle.setup(width=800, height=600, startx=0, starty=0)
turtle.done()
4.turtle.delay():用于设置画笔动画的延迟时间,单位是毫秒
import turtle
turtle.delay(100)
turtle.forward(100)
turtle.done()
5.turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
arg是要写入的文本内容,move是一个布尔值,表示是否移动海龟以便在写入文本后继续移动,align表示文本对齐方式,font是字体参数,包括字体名称、大小和样式。
import turtle
# 创建Turtle对象
t = turtle.Turtle()
# 写入文本
t.write("Hello, world!", move=True, align="center", font=("Arial", 20, "normal"))
# 隐藏海龟
t.hideturtle()
# 等待用户关闭窗口
turtle.done()
6.turtle.reset()函数
import turtle
# 创建乌龟并绘制一个正方形
t = turtle.Turtle()
for i in range(4):
t.forward(100)
t.right(90)
# 重置窗口状态并清除画布
turtle.reset()
# 再次创建乌龟并绘制一个圆形
t = turtle.Turtle()
t.circle(50)
turtle.done()
7.turtle.undo()
import turtle
turtle.forward(50) # 向前走50个像素
turtle.undo() # 撤销最近的操作,turtle 回到初始位置
turtle.left(90) # 左转90度
turtle.forward(100) # 向前走100个像素
turtle.undo() # 再次撤销最近的操作,turtle 回到初始位置
3.3.4其他函数
1.turtle.mainloop()
turtle.mainloop()
是一个turtle库中的函数,用于启动Tkinter的事件循环。它使得turtle绘图窗口可以保持打开状态并等待用户交互,直到用户关闭窗口。
import turtle
# 定义一个正方形函数
def square():
for i in range(4):
turtle.forward(100)
turtle.left(90)
# 绘制一个红色正方形
turtle.color('red')
square()
# 进入主事件循环,等待用户交互
turtle.mainloop()
2.turtle.mode(mode=None)
参数:
mode
(可选):字符串类型,表示要设置的模式。可选值为standard
、logo
、world
。返回值:
- 如果省略参数,则返回当前的模式(字符串类型)。
- 如果提供了参数,则将窗口模式设置为指定的模式。
import turtle
turtle.mode() # 返回当前窗口模式,'standard'为默认值
turtle.mode('logo') # 设置窗口模式为'logo'
3.turtle.delay(delay=None)
delay
是延迟时间,单位是毫秒。当delay
为 None 或者不提供参数时,函数返回当前的延迟时间。
import turtle
# 设置绘图延迟时间为 100 毫秒
turtle.delay(100)
# 绘制一个正方形
for i in range(4):
turtle.forward(100)
turtle.left(90)
turtle.done()
4.turtle.delay()
import turtle
# 设置动画延迟时间
turtle.delay(100)
# 绘制蓝色正方形
turtle.color('blue')
turtle.begin_fill()
for i in range(4):
turtle.forward(100)
turtle.left(90)
turtle.end_fill()
turtle.done()
应用小猪佩奇
import turtle as t
t.pensize(4)
t.hideturtle()
t.colormode(255)
t.color((255, 155, 192), "pink")
t.setup(840, 500)
t.speed(20)
# 鼻子
t.pu()
t.goto(-100, 100)
t.pd()
t.seth(-30)
t.begin_fill()
a = 0.4
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a = a + 0.08
t.lt(3) # 向左转3度
t.fd(a) # 向前走a的步长
else:
a = a - 0.08
t.lt(3)
t.fd(a)
t.end_fill()
t.pu()
t.seth(90)
t.fd(25)
t.seth(0)
t.fd(10)
t.pd()
t.pencolor(255, 155, 192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160, 82, 45)
t.end_fill()
t.pu()
t.seth(0)
t.fd(20)
t.pd()
t.pencolor(255, 155, 192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160, 82, 45)
t.end_fill()
# 头
t.color((255, 155, 192), "pink")
t.pu()
t.seth(90)
t.fd(41)
t.seth(0)
t.fd(0)
t.pd()
t.begin_fill()
t.seth(180)
t.circle(300, -30)
t.circle(100, -60)
t.circle(80, -100)
t.circle(150, -20)
t.circle(60, -95)
t.seth(161)
t.circle(-300, 15)
t.pu()
t.goto(-100, 100)
t.pd()
t.seth(-30)
a = 0.4
for i in range(60):
if 0 <= i < 30 or 60 <= i < 90:
a = a + 0.08
t.lt(3) # 向左转3度
t.fd(a) # 向前走a的步长
else:
a = a - 0.08
t.lt(3)
t.fd(a)
t.end_fill()
# 耳朵
t.color((255, 155, 192), "pink")
t.pu()
t.seth(90)
t.fd(-7)
t.seth(0)
t.fd(70)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50, 50)
t.circle(-10, 120)
t.circle(-50, 54)
t.end_fill()
t.pu()
t.seth(90)
t.fd(-12)
t.seth(0)
t.fd(30)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50, 50)
t.circle(-10, 120)
t.circle(-50, 56)
t.end_fill()
# 眼睛
t.color((255, 155, 192), "white")
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-95)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
t.color((255, 155, 192), "white")
t.pu()
t.seth(90)
t.fd(-25)
t.seth(0)
t.fd(40)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
# 腮
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(-95)
t.seth(0)
t.fd(65)
t.pd()
t.begin_fill()
t.circle(30)
t.end_fill()
# 嘴
t.color(239, 69, 19)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(-100)
t.pd()
t.seth(-80)
t.circle(30, 40)
t.circle(40, 80)
# 身体
t.color("red", (255, 99, 71))
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-78)
t.pd()
t.begin_fill()
t.seth(-130)
t.circle(100, 10)
t.circle(300, 30)
t.seth(0)
t.fd(230)
t.seth(90)
t.circle(300, 30)
t.circle(100, 3)
t.color((255, 155, 192), (255, 100, 100))
t.seth(-135)
t.circle(-80, 63)
t.circle(-150, 24)
t.end_fill()
# 手
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(-40)
t.seth(0)
t.fd(-27)
t.pd()
t.seth(-160)
t.circle(300, 15)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-10)
t.circle(-20, 90)
t.pu()
t.seth(90)
t.fd(30)
t.seth(0)
t.fd(237)
t.pd()
t.seth(-20)
t.circle(-300, 15)
t.pu()
t.seth(90)
t.fd(20)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-170)
t.circle(20, 90)
# 脚
t.pensize(10)
t.color((240, 128, 128))
t.pu()
t.seth(90)
t.fd(-75)
t.seth(0)
t.fd(-180)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
t.pensize(10)
t.color((240, 128, 128))
t.pu()
t.seth(90)
t.fd(40)
t.seth(0)
t.fd(90)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
# 尾巴
t.pensize(4)
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(70)
t.seth(0)
t.fd(95)
t.pd()
t.seth(0)
t.circle(70, 20)
t.circle(10, 330)
t.circle(70, 30)
t.exitonclick()
应用圣诞树
import turtle
import random
# 定义画彩灯的方法
def drawlight():
# 随机选择颜色并画彩灯
if random.randint(0, 50) == 0:
turtle.color('tomato')
turtle.circle(6)
elif random.randint(0, 50) == 1:
turtle.color('orange')
turtle.circle(6)
elif random.randint(0, 100) == 2:
turtle.color('purple')
turtle.circle(6)
else:
# 其余的随机数情况下画空的树枝
turtle.color('dark green')
# 画树叶的方法
def tree(d, s):
if d <= 0:
return
turtle.forward(s)
tree(d - 1, s * 0.8)
turtle.right(120)
tree(d - 3, s * 0.5)
turtle.right(120)
tree(d - 3, s * 0.5)
# 在分支的末端画彩灯
drawlight()
turtle.right(120)
turtle.backward(s)
# 画雪花的方法
def drawsnow():
turtle.ht()
turtle.pensize(2)
for i in range(100):
turtle.pencolor('white')
turtle.pu()
# 随机生成坐标
turtle.setx(random.randint(-350, 350))
turtle.sety(random.randint(-100, 350))
turtle.pd()
dens = 6 # 雪花瓣数
snowsize = random.randint(5, 10)
for j in range(dens):
turtle.forward(int(snowsize))
turtle.backward(int(snowsize))
turtle.right(int(360 / dens))
n = 100
turtle.speed('fastest')
turtle.screensize(bg='black')
turtle.left(90)
turtle.forward(3 * n)
turtle.color("orange", "yellow")
turtle.left(126)
# 画太阳花
for i in range(5):
turtle.forward(n / 5)
turtle.right(144)
turtle.forward(n / 5)
turtle.left(72)
turtle.end_fill()
turtle.right(126)
turtle.color("dark green")
turtle.backward(n * 4.8)
# 画树
tree(15, n)
turtle.backward(n / 5)
# 画雪花
drawsnow()
turtle.done()