python第二章课后习题

TempConvert.py

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

exchange rate.py

money = input("请输入:")
if money[0] in ['$']:
a = (eval(money[1:])*6.473)
print("人民币是{:.2f}元".format(a))
elif money[0] in ['¥']:
b =(eval(money[1:]))/6.473
print("美元是{:.2f}元".format(b))
else:
print("输入格式错误")

weight = input("请输入:")
if weight[-2:] in ['千克']:
a = (eval(weight[0:-2])*2.2046)
print("重量是{:.2f}磅".format(a))
elif weight[-2:] in ['磅']:
b =(eval(weight[0:-2]))/2.2046
print("重量是{:.2f}千克".format(b))
else:
print("输入格式错误")

DrawColorfulPython.py

import turtle

定义颜色列表(可根据需要调整颜色顺序)

colors = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple']

turtle.setup(650, 350, 200, 200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.seth(-40)

循环绘制彩色蟒蛇

for i in range(4):
# 设置当前颜色(循环取色)
turtle.pencolor(colors[i % len(colors)])
turtle.circle(40, 80)
turtle.circle(-40, 80)

绘制蟒蛇头部

turtle.pencolor(colors[4 % len(colors)])
turtle.circle(40, 80/2)
turtle.pencolor(colors[5 % len(colors)])
turtle.fd(40)
turtle.pencolor(colors[6 % len(colors)])
turtle.circle(16, 180)
turtle.pencolor(colors[0 % len(colors)])
turtle.fd(40 * 2/3)

turtle.done()

import turtle

def draw_equilateral_triangle():
# 设置画笔
pen = turtle.Turtle()
pen.speed(5) # 设置绘制速度

# 绘制等边三角形
for _ in range(3):
    pen.forward(100)  # 向前移动100单位
    pen.left(120)     # 向左转120度

# 结束绘制
turtle.done()

调用函数绘制等边三角形

draw_equilateral_triangle()

DrawPython.py

import turtle
turtle.setup(500.500)
turtle.fd(100)
turtle.left(120)
turtle.fd(100)
turtle.left(120)
turtle.fd(100)
turtle.left(120)
turtle.fd(50)
turtle.left(60)
turtle.fd(50)
turtle.left(120)
turtle.fd(50)
turtle.left(120)
turtle.fd(50)

DrawPython.py

import turtle
turtle.setup(500.500)
turtle.left(30)
turtle.fd(180)
turtle.right(120)
turtle.fd(270)
turtle.right(120)
turtle.fd(270)
turtle.right(120)
turtle.fd(90)
turtle.left(60)
turtle.fd(90)
turtle.right(120)
turtle.fd(270)
turtle.right(120)
turtle.fd(270)
turtle.right(120)
turtle.fd(180)
turtle.done()

import turtle

def draw_square_spiral():
# 设置画笔
pen = turtle.Turtle()
pen.speed(10) # 设置绘制速度

# 绘制正方形螺旋线
length = 10  # 初始长度
for _ in range(50):  # 循环50次
    pen.forward(length)
    pen.left(90)     # 向左转90度
    length += 5      # 每次增加长度

# 结束绘制
turtle.done()

调用函数绘制正方形螺旋线

draw_square_spiral()

posted @ 2025-03-16 19:35  kk/  阅读(52)  评论(0)    收藏  举报