您好,欢迎来到百家汽车网。
搜索
您的当前位置:首页python程序-九九乘法表-圣诞树-烟花-时间交互-小乌龟-ATM-樱花树-温度转换-温度进度表-Π的计算-智能垃圾桶分类

python程序-九九乘法表-圣诞树-烟花-时间交互-小乌龟-ATM-樱花树-温度转换-温度进度表-Π的计算-智能垃圾桶分类

来源:百家汽车网

以下是我自己找到,或者自己编写的程序,一些有意思的程序,如果有问题欢迎在评论区交流!

1.九九乘法表

for x in range(10):
    for j in range(1, x+1):
        print(f"%d * %d = {x * j} " % (j, x), end='')
    print()
    

2.圣诞树+烟花

"""
name:圣诞树+烟火
author:Babysen
"""

import turtle as t
import random
import threading
import time
import tkinter as tk
import math
from math import cos, sin, atan, sqrt
import numpy as np
w = t.Screen()
w.bgcolor('wheat')  # 定义背景颜色


# 心函数
def loving_heart(r):
    ll = 2 * r
    t.left(45)
    t.forward(ll)
    t.circle(r, 180)
    t.right(90)
    t.circle(r, 180)
    t.forward(ll)


# 星函数
def loving_star(k):
    for p in range(5):
        t.forward(k / 5)
        t.right(144)
        t.forward(k / 5)
        t.left(72)


# 树函数(递归)
def tree(d, s):
    if d <= 0:
        return
    t.width(5)
    t.forward(s)
    tree(d - 1, s * .8)
    t.right(120)
    tree(d - 3, s * .5)
    t.right(120)
    tree(d - 3, s * .5)
    t.right(120)
    t.backward(s)  # 回退函数


# 画爱心部分
t.penup()
t.goto(0, 200)  # 设置起点位置
t.pendown()
t.pencolor('red')  # 设置画笔颜色
t.color('red')
t.begin_fill()  # 对图形进行填充
loving_heart(20)  # 执行画爱心函数
t.end_fill()

# 画树部分
n = 100
t.speed(0)
# t.Turtle().screen.delay(0)
t.right(225)
t.color("dark green")
t.backward(n * 4.8)
tree(15, n)
t.backward(n / 5)

# 绘制落叶
for i in range(100):
    a = 100 - 200 * random.random()
    b = 10 - 20 * random.random()
    t.speed(0)
    t.up()
    t.forward(b)
    t.left(90)
    t.forward(a)
    t.down()
    if random.randint(1, 2) == 1:
        t.color('tomato')
    else:
        t.color('wheat')
    t.circle(4)
    t.up()
    t.backward(a)
    t.right(90)
    t.backward(b)


# 绘制雪花
def drawsnow():  # 定义画雪花的方法
    t.speed(0)
    t.ht()  # 隐藏笔头,ht=hideturtle
    t.pensize(2)  # 定义笔头大小
    for p in range(160):  # 画多少雪花
        t.pencolor("white")  # 定义画笔颜色为白色,其实就是雪花为白色
        t.pu()  # 提笔,pu=penup
        t.setx(random.randint(-350, 350))  # 定义x坐标,随机从-350到350之间选择
        t.sety(random.randint(-100, 350))  # 定义y坐标,注意雪花一般在地上不会落下,所以不会从太小的纵座轴开始
        t.pd()  # 落笔,pd=pendown
        dens = 6  # 雪花瓣数设为6
        snowsize = random.randint(2, 10)  # 定义雪花大小
        for j in range(dens):  # 就是6,那就是画5次,也就是一个雪花五角星
            # t.forward(int(snowsize))  #int()取整数
            t.fd(int(snowsize))
            t.backward(int(snowsize))
            # t.bd(int(snowsize))  #注意没有bd=backward,但有fd=forward,小bug
            t.right(int(360 / dens))  # 转动角度


drawsnow()

# 画五角星
for i in range(-200, 200, 20):
    t.penup()
    t.goto(i, 300)  # 设置起点位置
    t.pendown()
    t.pencolor('yellow')  # 设置画笔颜色
    t.color('yellow')
    t.begin_fill()  # 对图形进行填充
    loving_star(30)
    t.end_fill()
    t.right(0)

for i in range(-150, 150, 20):
    t.penup()
    t.goto(i, 280)  # 设置起点位置
    t.pendown()
    t.pencolor('yellow')  # 设置画笔颜色
    t.color('yellow')
    t.begin_fill()  # 对图形进行填充
    loving_star(30)
    t.end_fill()
    t.right(0)

for i in range(-100, 100, 20):
    t.penup()
    t.goto(i, 260)  # 设置起点位置
    t.pendown()
    t.pencolor('yellow')  # 设置画笔颜色
    t.color('yellow')
    t.begin_fill()  # 对图形进行填充
    loving_star(30)
    t.end_fill()
    t.right(0)

for i in range(-50, 50, 20):
    t.penup()
    t.goto(i, 240)  # 设置起点位置
    t.pendown()
    t.pencolor('yellow')  # 设置画笔颜色
    t.color('yellow')
    t.begin_fill()  # 对图形进行填充
    loving_star(30)
    t.end_fill()
    t.right(0)

for i in range(-20, 21, 20):
    t.penup()
    t.goto(i, 220)  # 设置起点位置
    t.pendown()
    t.pencolor('yellow')  # 设置画笔颜色
    t.color('yellow')
    t.begin_fill()  # 对图形进行填充
    loving_star(30)
    t.end_fill()
    t.right(0)

# 写下署名
t.color("white")  # 填充颜色
t.up()  # 抬笔
t.goto(170, -240)
t.down()  # 落笔
t.write("Author:Babysen", font=("Times New Roman", 18, "normal"))
t.ht()
# t.done()
t.hideturtle()
time.sleep(2)

# 烟火
WIDTH = 0
HEIGHT = 0
ORI = (0, 0)
COLOR = {'0': '#070920', 'navyblue': '#000080'}
FIRE = []


def setParam():
    global WIDTH
    global HEIGHT
    global ORI
    global FIRE
    WIDTH = t.window_width()
    HEIGHT = t.window_height()
    ORI = (0, -HEIGHT / 2)
    # gold
    FIRE.append(['white', '#FFD700', '#DAA520', '#BDB76B', ])
    # red
    FIRE.append(['white', '#F08080', '#A0522D', '#DC143C', ])
    # green
    FIRE.append(['white', '#7FFF00', '#32CD32', '#0000', ])
    # cyan
    FIRE.append(['white', '#40E0D0', '#00FFFF', '#008080', ])
    # pink
    FIRE.append(['white', '#FF69B4', '#FF1493', '#8B008B', ])
    # buff
    FIRE.append(['white', '#FFE4C4', '#FFDAB9', '#F0FFF0', ])
    # bluish
    FIRE.append(['white', '#ADD8E6', '#AFEEEE', '#00BFFF', ])


def dist(o, m):  # 距离
    return ((o - m) * (o - m)).sum()


def shoot():
    t.tracer(4)  # 在循环中,图形将一次画出4次循环的图
    t.pu()
    target = np.array((np.random.randint(-WIDTH // 6, WIDTH // 6),
                       HEIGHT // 6))  # 都在同一高度
    angle = atan((target - ORI)[1] / (target - ORI)[0])
    if angle < 0:
        angle += math.pi  # 纠正负方向
    unit = np.array([cos(angle), sin(angle)])  # 方向向量
    print('angle: ', angle)
    print('target: ', target)
    # 镜头的顺序坐标
    seq = np.array([ORI, ORI - 55 * unit, ORI - 105 * unit, ORI - 155 * unit])
    t.speed(0)  # 瞬动
    while dist(seq[0], target) > 120:  # 如果没有到达爆炸中心
        seq = (seq[0] + 30 * unit[0], seq[1] + 30 * unit[1])  # 分别对应位置相加

        t.goto(float(seq[1]))
        t.pd()
        t.width(3)
        t.pencolor('white')
        t.goto(seq[0])
        t.pu()

        t.goto(seq[2])
        t.pd()
        t.width(3)
        t.pencolor('yellow')
        t.goto(seq[1])
        t.pu()

        # 清除发射上去的光束尾迹
        t.goto(seq[3])
        t.pd()
        t.width(10)
        t.pencolor(COLOR['0'])
        t.goto(seq[2])
        t.pu()
        time.sleep(0.05)

    # 发射上去的光束最后清除
    t.pd()
    t.width(10)
    t.goto(seq[0])
    t.pu()
    time.sleep(0.1)
    return target  # 就在爆炸中心


def explode(center):
    number = np.random.randint(50, 100)  # 光束数
    colormode = np.random.randint(0, 5)
    unit = np.array([])  # 方向向量
    spd = []  # 每个光束的速度
    seq = []  # 每个波束的顺序坐标
    if colormode <= 1:
        coloridx = [np.random.randint(0, len(FIRE))]
    elif colormode == 2:
        coloridx = [np.random.randint(0, len(FIRE)),
                    np.random.randint(0, len(FIRE))]
    elif colormode == 3:
        coloridx = [np.random.randint(0, len(FIRE)),
                    np.random.randint(0, len(FIRE)),
                    np.random.randint(0, len(FIRE))]
    elif colormode == 4:
        coloridx = []

    # 不同大小烟花的步骤
    steps = int((number ** 0.5) * 2)

    # 初始化
    for z in range(number):
        angle = np.random.rand() * 2 * math.pi - math.pi
        unit = np.append(unit, [cos(angle), sin(angle)]).reshape(-1, 2)
        seq = np.append(
            seq,
            [center,
             center - 10 * unit[z], center - 50 * unit[z],
             center - 90 * unit[z], center - 130 * unit[z],
             center - 135 * unit[z]]
        )
        spd.append(int(15 + (np.random.rand() - 0.5) * 5))

        if colormode <= 1:
            coloridx.append(coloridx[0])
        elif colormode == 2:
            coloridx.append(coloridx[np.random.randint(0, 2)])
        elif colormode == 3:
            coloridx.append(coloridx[np.random.randint(0, 3)])
        elif colormode == 4:
            coloridx.append(np.random.randint(0, len(FIRE)))

    seq = seq.reshape([-1, 6, 2]).astype(np.int32)
    t.tracer(0x3f3f3f3f)  # 关闭自动更新,0x3f3f3f3f是一个大数字

    for stage in range(steps):
        for z in range(number):
            seq[z] = seq[z] + spd[z] * unit[z]
            seq[z][4] = center
            for cur in range(4):
                t.pu()
                t.goto(seq[z][cur + 1])
                t.pd()
                t.pencolor(FIRE[coloridx[z]][cur])
                t.width(4 - cur)
                t.goto(seq[z][cur])
                t.pu()
        if stage >= 5:  # 等待所有光束就位
            t.update()
            time.sleep(0.04)

    # 清除每次绽放的烟花
    for cur in range(4, -1, -1):
        for x in range(number):
            t.pu()
            t.goto(seq[x][cur + 1])
            t.pd()
            t.pencolor(COLOR['0'])
            t.width(100)
            t.goto(seq[x][cur])
            t.pu()
        time.sleep(0.02)
        t.update()


def main():
    t.setup(700, 750, 100, 0)
    setParam()
    while True:
        point = shoot()
        explode(point)
    exitonclick()  # 在任何位置单击退出


if __name__ == '__main__':
    main()

3.时间的交互

from datetime import datetime
now = datetime.now()
print(now)
now.strftime("%x")
now.strftime("%x")  # 时间的交互

4.烟花程序

import pygame
from random import randint, uniform, choice
import math

vector = pygame.math.Vector2
gravity = vector(0, 0.3)
DISPLAY_WIDTH = DISPLAY_HEIGHT = 800

trail_colours = [(45, 45, 45), (60, 60, 60), (75, 75, 75),
                 (125, 125, 125), (150, 150, 150)]
dynamic_offset = 1
static_offset = 5


class Firework:

    def __init__(self):
        self.colour = (randint(0, 255), randint(0, 255), randint(0, 255))
        self.colours = (
            (randint(0, 255), randint(0, 255), randint(0, 255)
             ), (randint(0, 255), randint(0, 255), randint(0, 255)),
            (randint(0, 255), randint(0, 255), randint(0, 255)))
        self.firework = Particle(randint(0, DISPLAY_WIDTH), DISPLAY_HEIGHT, True,
                                 self.colour)  # Creates the firework particle
        self.exploded = False
        self.particles = []
        self.min_max_particles = vector(100, 225)

    def update(self, win):  # called every frame
        if not self.exploded:
            self.firework.apply_force(gravity)
            self.firework.move()
            for tf in self.firework.trails:
                tf.show(win)

            self.show(win)

            if self.firework.vel.y >= 0:
                self.exploded = True
                self.explode()
        else:
            for particle in self.particles:
                particle.apply_force(
                    vector(gravity.x + uniform(-1, 1) / 20, gravity.y / 2 + (randint(1, 8) / 100)))
                particle.move()
                for t in particle.trails:
                    t.show(win)
                particle.show(win)

    def explode(self):
        amount = randint(int(self.min_max_particles.x), int(self.min_max_particles.y))
        for i in range(amount):
            self.particles.append(
                Particle(self.firework.pos.x, self.firework.pos.y, False, self.colours))

    def show(self, win):
        pygame.draw.circle(win, self.colour, (int(self.firework.pos.x), int(
            self.firework.pos.y)), self.firework.size)

    def remove(self):
        if self.exploded:
            for p in self.particles:
                if p.remove is True:
                    self.particles.remove(p)

            if len(self.particles) == 0:
                return True
            else:
                return False


class Particle:

    def __init__(self, x, y, firework, colour):
        self.firework = firework
        self.pos = vector(x, y)
        self.origin = vector(x, y)
        self.radius = 20
        self.remove = False
        self.explosion_radius = randint(5, 18)
        self.life = 0
        self.acc = vector(0, 0)
        # trail variables
        self.trails = []  # stores the particles trail objects
        self.prev_posx = [-10] * 10  # stores the 10 last positions
        self.prev_posy = [-10] * 10  # stores the 10 last positions

        if self.firework:
            self.vel = vector(0, -randint(17, 20))
            self.size = 5
            self.colour = colour
            for i in range(5):
                self.trails.append(Trail(i, self.size, True))
        else:
            self.vel = vector(uniform(-1, 1), uniform(-1, 1))
            self.vel.x *= randint(7, self.explosion_radius + 2)
            self.vel.y *= randint(7, self.explosion_radius + 2)
            self.size = randint(2, 4)
            self.colour = choice(colour)
            for i in range(5):
                self.trails.append(Trail(i, self.size, False))

    def apply_force(self, force):
        self.acc += force

    def move(self):
        if not self.firework:
            self.vel.x *= 0.8
            self.vel.y *= 0.8

        self.vel += self.acc
        self.pos += self.vel
        self.acc *= 0

        if self.life == 0 and not self.firework:  # check if particle is outside explosion radius
            distance = math.sqrt((self.pos.x - self.origin.x)
                                 ** 2 + (self.pos.y - self.origin.y) ** 2)
            if distance > self.explosion_radius:
                self.remove = True

        self.decay()

        self.trail_update()

        self.life += 1

    def show(self, win):
        pygame.draw.circle(win, (self.colour[0], self.colour[1], self.colour[2], 0), (int(self.pos.x), int(self.pos.y)),
                           self.size)

    def decay(self):  # random decay of the particles
        if 50 > self.life > 10:  # early stage there is a small chance of decay
            ran = randint(0, 30)
            if ran == 0:
                self.remove = True
        elif self.life > 50:
            ran = randint(0, 5)
            if ran == 0:
                self.remove = True

    def trail_update(self):
        self.prev_posx.pop()
        self.prev_posx.insert(0, int(self.pos.x))
        self.prev_posy.pop()
        self.prev_posy.insert(0, int(self.pos.y))

        for n, t in enumerate(self.trails):
            if t.dynamic:
                t.get_pos(self.prev_posx[n + dynamic_offset],
                          self.prev_posy[n + dynamic_offset])
            else:
                t.get_pos(self.prev_posx[n + static_offset],
                          self.prev_posy[n + static_offset])


class Trail:

    def __init__(self, n, size, dynamic):
        self.pos_in_line = n
        self.pos = vector(-10, -10)
        self.dynamic = dynamic

        if self.dynamic:
            self.colour = trail_colours[n]
            self.size = int(size - n / 2)
        else:
            self.colour = (255, 255, 200)
            self.size = size - 2
            if self.size < 0:
                self.size = 0

    def get_pos(self, x, y):
        self.pos = vector(x, y)

    def show(self, win):
        pygame.draw.circle(win, self.colour, (int(
            self.pos.x), int(self.pos.y)), self.size)


def update(win, fireworks):
    for fw in fireworks:
        fw.update(win)
        if fw.remove():
            fireworks.remove(fw)

    pygame.display.update()


def main():
    pygame.init()
    pygame.display.set_caption("Fireworks in Pygame")
    win = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    clock = pygame.time.Clock()

    fireworks = [Firework() for _ in range(2)]  # create the first fireworks
    running = True

    while running:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.KEYDOWN:  # Change game speed with number keys
                if event.key == pygame.K_1:
                    fireworks.append(Firework())
                if event.key == pygame.K_2:
                    for i in range(10):
                        fireworks.append(Firework())
        win.fill((20, 20, 30))  # draw background

        if randint(0, 20) == 1:  # create new firework
            fireworks.append(Firework())

        update(win, fireworks)

        # stats for fun
        # total_particles = 0
        # for f in fireworks:
        #    total_particles += len(f.particles)

        # print(f"Fireworks: {len(fireworks)}\nParticles: {total_particles}\n\n")

    pygame.quit()
    quit()


main()

5.小乌龟

from turtle import *  # 从turtle库中引入所有的命令
import turtle as t  # 引入turtle库把它叫做t
import pygame as p  # 引入turtle库把它叫做p
p.init()  # 初始化p的所有模块

# 设置标题
t.title("欢迎来到海龟运动会之神奇海龟对决兔子")
# 设置背景色
t.bgcolor("pink")

# 小红旗
t.penup()
t.speed(1)
t.goto(200, 0)  # 直接开跳
t.pendown()
t.color("red")
t.begin_fill()
t.left(90)
t.forward(60)
t.right(90)
t.forward(40)
t.right(150)
t.forward(50)
t.end_fill()
t.penup()

# 兔子
rabbit = Turtle()  # 定义兔子
rabbit.hideturtle()  # 让兔子
rabbit.shape('turtle')  # 兔子的形状是一只海龟(滑稽脸)
rabbit.color("green")
rabbit.up()  # 将兔子移动到起点,准备比赛
rabbit.back(300)  # 把兔子往后移300
rabbit.showturtle()  # 让兔子显露出来
rabbit.down()  # 兔子移动时划线


def rabbitmove():  # 定义一个新的函数 兔子移动
    if usedtime < 50:  # 如果用时小于50
        rabbit.forward(3)  # 兔子向前奔跑
        rabbit.color("green")  # 兔子的颜色是绿色
    elif usedtime < 415:  # 如果用时 50<=usedtime<415 兔子就去睡觉,位移不变
        rabbit.forward(0)  # 兔子向前0
    else:  # 否则就追赶
        rabbit.forward(6)  # 兔子向前4

# 乌龟


tortoise = Turtle()  # 引入乌龟图案
tortoise.hideturtle()  # 让乌龟
tortoise.shape('turtle')  # 确定乌龟的形状
tortoise.color("purple")  # 确定乌龟的颜色
tortoise.pensize(3)  # 确定笔画的粗细
tortoise.up()  # 将乌龟移动到起点,准备比赛
tortoise.back(300)  # 将乌龟后移300
tortoise.showturtle()  # 把乌龟显露出来
tortoise.down()  # 乌龟移动时划线


def tortoisemove():  # 定义一个新的函数 乌龟移动
    tortoise.forward(1)  # 乌龟一直在缓慢的爬行
    if usedtime % 2 == 0:
        tortoise.color("purple")
    else:
        tortoise.color("red")

# 背景音


def musics():
    file = r'C:\Users\郭钊\Desktop\work space\1.mp3'
    p.mixer.init()    # 初始化混音器
    p.mixer.music.load(file)  # 加载文件
    p.mixer.music.play()  # 播放音乐


usedtime = 0  # 定义用时赋初值为0


def move():  # 定义函数移动
    global usedtime  # 全局形式 移动均参照usedtime
    rabbitposition = rabbit.xcor()  # 兔子的位置是兔子的x坐标
    tortoiseposition = tortoise.xcor()  # 乌龟的位置是乌龟的x坐标
    if max(rabbitposition, tortoiseposition) > 200:  # 如果兔子和乌龟的位置中最大的超过200
        writer = Turtle()  # writer定义为Turtle
        writer.hideturtle()  # 隐藏乌龟(兔子)
        if tortoiseposition > 200:  # 如果乌龟的位置大于200
            msg = 'Tortoise win!'  # 给msg(message)赋值字符串 rabbit win!
        else:  # 否则就给msg赋字符串 tortoise win!
            msg = 'Rabbit win!'
        writer.write(msg, align='center', font=('simfang', 30, 'bold'))  # 模块写入设置
        # 输入字样 对齐方式 字体为仿宋,30号,黑体的
        p.mixer.music.fadeout(700)  # 控制音乐淡出
    else:  # 否则就移动
        rabbitmove()  # 兔子移动
        tortoisemove()  # 乌龟移动
        ontimer(move, 100)  # 定时让它们有动画效果
        usedtime = usedtime+1  # 循环,用时+1


# musics()
ontimer(move, 100)    # 比赛开始,定时
rabbit = Turtle()  # 定义兔子
rabbit.hideturtle()  # 让兔子
rabbit.shape('turtle')  # 兔子的形状是一只海龟(滑稽脸)
rabbit.color("green")
rabbit.up()  # 将兔子移动到起点,准备比赛
rabbit.back(300)  # 把兔子往后移300
rabbit.showturtle()  # 让兔子显露出来
rabbit.down()  # 兔子移动时划线

# 乌龟
tortoise = Turtle()  # 引入乌龟图案
# tortoise.hideturtle()  # 让乌龟
tortoise.shape('turtle')  # 确定乌龟的形状
tortoise.color("purple")  # 确定乌龟的颜色
tortoise.pensize(3)  # 确定笔画的粗细
tortoise.up()  # 将乌龟移动到起点,准备比赛
tortoise.back(3000)  # 将乌龟后移300
tortoise.showturtle()  # 把乌龟显露出来
tortoise.down()  # 乌龟移动时划线


turtle = Turtle()
turtle.shape('turtle')
turtle.forward(200)

rabbit = Turtle()
rabbit.shape('turtle')
# 小红旗
while True:
    move()
    tortoisemove()

6. ATM简单程序

money = 50000000
name = input("请入你的名字:")
print(f"{name},你好,欢迎来到ATM,请选择操作:")


def init():
    """
    初始化界面输出
    :return: None
    """

    print("查询余额\t[输入1]")
    print("存款    \t[输入2]")
    print("取款    \t[输入3]")
    print("退出    \t[输入4]")


def model(x):
    global money
    """
    :param x: 选择的模式
    :return:
    """
    if x == 1:
        print("----------------------查询余额-----------------------")
        print(f"{name},您好,您的余额剩余:{money}")
        return "SUCCESS"

    elif x == 2:

        print("----------------------存款-----------------------")
        add_money = int(input("请输入你存款的金额:"))
        money += add_money
        print(f"{name},您好,您的余额剩余:{money}")
        return "SUCCESS"
    elif x == 3:

        print("----------------------取款-----------------------")
        add_money = int(input("请输入你取款的金额:"))
        money -= add_money
        print(f"{name},您好,您的余额剩余:{money}")
        return "SUCCESS"
    elif x == 4:
        print("已成功退出,欢迎下次使用!")
        return None
    else:
        print("输入错误,已退出ATM")
        return None


init()
choice = int(input("请输入你的选择:"))

while model(choice) == "SUCCESS":
    choice_2 = int(input("请选择你接下来的操作:"))
    model(choice_2)
    choice = choice_2

7.樱花树代码

import turtle as T
import random
import time


# 画樱花的躯干(60,t)
def Tree(branch, x):
    time.sleep(0.0005)
    if branch > 3:
        if 8 <= branch <= 12:
            if random.randint(0, 2) == 0:
                x.color('snow')  # 白
            else:
                x.color('lightcoral')  # 淡珊瑚色
            x.pensize(branch / 3)
        elif branch < 8:
            if random.randint(0, 1) == 0:
                x.color('snow')
            else:
                x.color('lightcoral')  # 淡珊瑚色
            x.pensize(branch / 2)
        else:
            x.color('sienna')  # 赭(zhě)色
            x.pensize(branch / 10)  # 6
        x.forward(branch)
        a = 1.5 * random.random()
        x.right(20 * a)
        b = 1.5 * random.random()
        Tree(branch - 10 * b, x)
        x.left(40 * a)
        Tree(branch - 10 * b, x)
        x.right(20 * a)
        x.up()
        x.backward(branch)
        x.down()


# 掉落的花瓣
def Petal(m, x):
    for i in range(m):
        a = 200 - 400 * random.random()
        b = 10 - 20 * random.random()
        x.up()
        x.forward(b)
        x.left(90)
        x.forward(a)
        x.down()
        x.color('lightcoral')  # 淡珊瑚色
        x.circle(1)
        x.up()
        x.backward(a)
        x.right(90)
        x.backward(b)


# 绘图区域
t = T.Turtle()
# 画布大小
w = T.Screen()
t.hideturtle()  # 隐藏画笔
t.getscreen().tracer(5, 0)
w.bgcolor('wheat')  # 设置窗口背景颜色为小麦色
t.left(90)
t.up()
t.backward(150)
t.down()
t.color('sienna')

# 画樱花的躯干
Tree(60, t)
# 掉落的花瓣
Petal(200, t)
w.exitonclick()
T.done()

8.温度转换

# TempConvert.py
TempStr = input("请输入带有符号的温度值: ")
print(eval(TempStr[0:-1]))
if TempStr[-1] in ['F', 'f']:
    C = (eval(TempStr[0:-1]) - 32)/1.8
    print("转换后的温度是{:.2f}C".format(C))
elif TempStr[-1] in ['C', 'c']:
    F = 1.8*eval(TempStr[0:-1]) + 32
    print("转换后的温度是{:.2f}F".format(F))
else:
    print("输入格式错误")

9.文件进度表

# TextProBarV3.py
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, '.'))

from tqdm import tqdm
from time import sleep

for i in tqdm(range(1000)):
    sleep(0.01)
#帅的一批

10. Π的计算

from random import random
from math import sqrt
from time import process_time   #perf_counter也可以使用,但准度好像不高
DARTS = 100000
hits = 0.0
process_time()
for i in range(1, DARTS+1):
    x, y = random(), random()
    dist = sqrt(x ** 2 + y ** 2)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits/DARTS)
print("Pi值是{}.".format(pi))
print("运行时间是: {:5.5}s".format(process_time()))

11.智能垃圾分类

trash = {
    '可回收垃圾': ["废纸", "塑料", "玻璃", "金属", "布料", "硬纸板"],
    '厨余垃圾': ["蔬菜", "瓜果", "饭菜", "花卉", "罐头", "骨头", "油脂类"],
    '有害垃圾': ["废电池", "废灯管", "废水银温度计", "过期药品"],
    '其他垃圾': ["卫生用纸", "塑料袋", "土", "一次性餐具", "头发", "玻璃碎片"]
}
#  塑料袋 土 花卉 罐头 布料 骨头
dustbin = {
    '可回收垃圾': '蓝色',
    '厨余垃圾': '绿色',
    '有害垃圾': '红色',
    '其他垃圾': '黑色'
}
classfy = {}
name = input("输入你要处理的垃圾,空格分割:")
Is = name.split(" ")

for name in Is:
    for key in trash:  # 取出key
        if name in trash[key]:
            if key not in classfy:
                classfy[key] = []  # 这里是给列表命名,然后成为字典
                classfy[key].append(name)
            else:
                classfy[key].append(name)
print("构建的垃圾分类的字典为\n", classfy)
for key in classfy:
    print("请将", end=' ')
    for name in classfy[key]:
        print(name, end=' ')
    print("投入{}垃圾桶。".format(dustbin[key]))

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baijiahaobaidu.com 版权所有 湘ICP备2023023988号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务