1. BMI 计算
import math
def main():
print("BMI 计算")
print("国内 BMI 正常值 :{}{}{}".format("18.5","-","24"))
print("国际 BMI 正常值 :{}{}{}".format("18.5","-","25"))
for i in range(3):
Weight=eval(input("Please enter your Weight(m)>>"))
Height=eval(input("Please enter your Height(kg)>>"))
#BMI = 体重(kg)/ 身高 2(m2)
IBM=Weight / (Height*Height)
print("The IBM is :",IBM)
if IBM>=18.5 and IBM<=24:
print("IBM正常 ")
else:
print("IBM不正常 ")
main()
2. 树的创建
# drawtree.py
from turtle import Turtle, mainloop
def tree(plist, l, a, f):
""" plist is list of pens
l is length of branch
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
if l > 5: #
lst = []
for p in plist:
#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
p.forward(l)#字母小写l,长度
#Create and return a clone of the turtle with same position, heading and turtle properties.
q=p.clone()
p.left(a) #Turn turtle left by angle units
q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
lst.append(p)#将元素增加到列表的最后
lst.append(q)
tree(lst, l*f, a, f)
def main():
p = Turtle()
p.color("green")
p.pensize(5)
#p.setundobuffer(None)
p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
#because hiding the turtle speeds up the drawing observably.
#p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
p.speed(10)
#TurtleScreen methods can then be called for that object.
p.left(90)# Turn turtle left by angle units. direction 调整画笔
p.penup() #Pull the pen up – no drawing when moving.
p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
p.pendown()# Pull the pen down – drawing when moving. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
#否则turtle一移动就会自动的把线画出来
#t = tree([p], 200, 65, 0.6375)
t = tree([p], 200, 65, 0.6375)
main()
3. 树的创建优化
# drawtree.py
from turtle import Turtle, mainloop
def tree(plist, l, a, f):
""" plist is list of pens
l is length of branch
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
if l > 5: #
lst = []
for p in plist:
#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
p.forward(l)#字母小写l,长度
#Create and return a clone of the turtle with same position, heading and turtle properties.
q=p.clone()
p.left(a) #Turn turtle left by angle units
q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
lst.append(p)#将元素增加到列表的最后
lst.append(q)
tree(lst, l*f, a, f)
def maketree(x,y):
p = Turtle()
p.color("green")
p.pensize(5)
#p.setundobuffer(None)
p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
#because hiding the turtle speeds up the drawing observably.
#p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
p.speed(10)
#TurtleScreen methods can then be called for that object.
p.left(90)# Turn turtle left by angle units. direction 调整画笔
p.penup() #Pull the pen up – no drawing when moving.
p.goto(x,y)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
p.pendown()# Pull the pen down – drawing when moving.
#这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
#否则turtle一移动就会自动的把线画出来
t = tree([p], 100, 65, 0.5)
def main():
maketree(200,-200)
maketree(-200,-200)
main()
4. 七段数码管
import turtle
import time
def drawDot():#画个空点
turtle.penup()
turtle.fd(5)
def drawLine(draw):
drawDot()
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
drawDot()
turtle.right(90)
def drawDigit(digit):#绘画日期
print (digit)
if digit in [2,3,4,5,6,8,9]:
drawLine(True)
else:
drawLine(False)
drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,6,8] else drawLine(False)
turtle.left(90)#转回来
drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)
drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)
turtle.left(180)
turtle.penup()#提起画笔,与 pendown()配对使用
turtle.fd(20)#沿着当前方向前进指定距离,数字之间的间隔
def drawDate(date): #date为日期,格式为‘%Y-%m=%d+’
turtle.pencolor("red")
for i in date:
if i =='-':
turtle.write('年',font=('Arial',18,"normal"))
turtle.pencolor("green")
turtle.fd(40)
elif i =='=':
turtle.write('月',font=('Arial',18,"normal"))
turtle.pencolor("blue")
turtle.fd(40)
elif i =='+':
turtle.write('日',font=('Arial',18,"normal"))
turtle.fd(40)
else:
#print (eval(i))
drawDigit(eval(i))
def main():
turtle.setup(800,350,200,200)#启动一个图形窗口
turtle.penup()#提起画笔,与 pendown()配对使用
turtle.fd(-300)#沿着当前方向前进指定距离
turtle.pensize(5)#设置画笔线条的粗细为指定大小
turtle.speed(1)
#根据一定格式,获取系统的当前时间
drawDate(time.strftime(('%Y-%m=%d+'),time.gmtime()))# 函数接收以时间元组,并返回以可读字符串表示的当地时间
turtle.hideturtle()#隐藏画笔的 turtle 形状
turtle.done()
main()
5.文件的输出
import turtle
def main():
outfile = open("outfile.txt","w")
outfile.writelines(["Hello"," ","world"])
outfile.close()
infile = open("outfile.txt","r")
data = infile.read()
print(data)
main()
6.文件拷贝
import turtle
def main():
infile = open("outfile.txt","r")
outfile = open("outfile2.txt","w")
countlines = countchars = 0
for line in infile:
countlines += 1
countchars += len(line)
outfile.write(line)
print(countlines,"lines and",countchars,"chars copied")
infile.close()
outfile.close()
main()
7. 根据数据文件在窗口中动态路径绘制
#根据数据文件在窗口中动态路径绘制
import turtle
def main():
#设置窗口信息
turtle.title('数据驱动的动态路径绘制')
turtle.setup(800, 600, 0, 0)
#设置画笔
pen = turtle.Turtle()
pen.color("red")
pen.width(5)
pen.shape("turtle")
pen.speed(5)
#读取文件
result=[]
file = open("data.txt","r")
for line in file:
result.append(list(map(float, line.split(','))))#append()方法用于在列表末尾添加新的对象。
print(result)
#动态绘制
for i in range(len(result)):
pen.color((result[i][3],result[i][4],result[i][5]))#RGB颜色
pen.forward(result[i][0])#300
if result[i][1]:#判断向左还是向右
pen.right(result[i][2])
else:
pen.left(result[i][2])
pen.goto(0,0)
if __name__ == '__main__':
main()
9.编写程序将电话簿TeleAddressBook.txt和电子邮件 EmailAddressBook.txt 合 并 为 一 个 完 整 的AddressBook.txt
#利用字典将两个通讯录文本合并为一个文本
def main():
ftele1=open('TeleAddressBook.txt','wt')#以文本写方式打开,只能写文件, 如果文件不存在,创建该文件
ftele2=open('EmailAddressBook.txt','wt')#如果文件已存在,先清空,再打开文件
ftele1.writelines(["姓名","\t","电话","\n","张三","\t","13189542121","\n","李四","\t","13189542325","\n"])#写入数据
ftele2.writelines(["姓名","\t","邮箱","\n","赵柳","\t","19484221123@qq.com","\n","王五","\t","19484225478@qq.com","\n"])#写入数据
ftele1=open('TeleAddressBook.txt','rb')#以二进制读方式打开,只能读文件 , 如果文件不存在,会发生异常
ftele2=open('EmailAddressBook.txt','rb')#以二进制读方式打开,只能读文件 , 如果文件不存在,会发生异常
ftele1.readline()#跳过第一行
ftele2.readline()#跳过第一行
lines1 = ftele1.readlines()
lines2 = ftele2.readlines()
dic1 = {}#字典方式保存
dic2 = {}#建立空字典dic1, dic2存储姓名、 电话和邮箱
for line in lines1:#获取第一个本文中的姓名和电话信息
elements = line.split()
#将文本读出来的bytes转换为str类型
dic1[elements[0]] = str(elements[1].decode('gbk'))
print("dic1=\n",dic1)
for line in lines2:#获取第二个本文中的姓名和电话信息
elements = line.split()
dic2[elements[0]] = str(elements[1].decode('gbk'))
print("dic2=\n",dic2)
###开始处理###
lines = []
lines.append('姓名\t 电话 \t\t 邮箱\n')
for key in dic1:
s= ''
if key in dic2.keys():
s = '\t'.join([str(key.decode('gbk')), dic1[key], dic2[key]])
s += '\n'
else:
s = '\t'.join([str(key.decode('gbk')), dic1[key], str(' ----- ')])
s += '\n'
lines.append(s)
print(lines)
for key in dic2:
s= ''
if key not in dic1.keys():
s = '\t'.join([str(key.decode('gbk')), str(' ----- '), dic2[key]])
s += '\n'
lines.append(s)
ftele3 = open('AddressBook.txt', 'w')
ftele3.writelines(lines)
ftele3.close()
ftele1.close()
ftele2.close()
print("The addressBooks are merged!")
if __name__ == "__main__":
main()