【初识python】几个有趣的小实例
程序员文章站
2024-02-24 17:56:16
...
这次写几个觉得有趣的小实例
1.进击の文本记录条
利用简单代码实现进度条
代码如下:
import time
scale = 50
print("执行开始".center(scale//2, "-"))#开始
start = time.perf_counter()
for i in range(scale+1):#利用循环实现进度条刷新
a = '*' * i
b = '.' * (scale - i)
c = (i/scale)*100
dur = time.perf_counter() - start
print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end='')
time.sleep(0.1)
print("\n"+"执行结束".center(scale//2,'-'))#结束
效果预览:
2.科赫de雪花
利用简单语法元素实现绘制科赫雪花
代码如下:
import turtle
def koch(size, n):
if n == 0:
turtle.fd(size)
else:
for angle in [0, 60, -120, 60]:
turtle.left(angle)
koch(size/3, n-1)
def main():
turtle.setup(600,600)
turtle.penup()
turtle.goto(-200, 100)
turtle.pendown()
turtle.pensize(2)
level = 1 # 1阶科赫雪花,阶数可更改
koch(400,level)
turtle.right(120)
koch(400,level)
turtle.right(120)
koch(400,level)
turtle.hideturtle()
main()
效果预览:
如果把阶数改为2
3.多边形的绘制
利用海龟库绘制一个炫彩的多边形
代码如下:
import turtle as t
t.bgcolor("black")
sides=eval(input("输入要绘制的边的数目,请输入2-6的数字!"))
colors=["red","yellow","green","blue","orange","purple"]
for x in range(150):
t.pencolor(colors[x%sides])
t.forward(x*3/sides+x)
t.left(360/sides+1)
t.width(x*sides/200)
t.exitonclick()
print("####结束####")
可以绘制一个炫彩多边形
效果如下:
4.动态小星空
画出一个简单的动态的星空
代码如下:
from turtle import *
from random import random,randint
screen = Screen()
width ,height = 800,600
screen.setup(width,height)
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()
效果如下:
上一篇: 最长回文