【初识python】几个有趣的小实例

这次写几个觉得有趣的小实例

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()

效果如下:
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

 江海寄余生 

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值