python语言程序设计-北京理工大学-嵩天等课件代码整理(转载)

 来源:https://www.cnblogs.com/zhenshj/p/8759080.html


#TempConvert.py
TempStr = input("请输入带有符号的温度值: ")
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("输入格式错误")
#PythonDraw.py
import turtle
turtle.setup(650, 350, 200, 200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
    turtle.circle(40, 80)
    turtle.circle(-40, 80)
turtle.circle(40, 80/2)
turtle.fd(40)
turtle.circle(16, 180)
turtle.fd(40 * 2/3)
turtle.done()
 

天天向上的力量 第一问

 

#DayDayUpQ1.py
dayup = pow(1.001, 365)
daydown = pow(0.999, 365)
print("向上:{:.2f},向下:{:.2f}".format(dayup, daydown))
 

 

天天向上的力量 第二问

 

#DayDayUpQ2.py
dayfactor = 0.005
dayup = pow(1+dayfactor, 365)
daydown = pow(1-dayfactor, 365)
print("向上:{:.2f},向下:{:.2f}".format(dayup, daydown))
 

 

天天向上的力量 第三问

 

#DayDayUpQ3.py
dayup = 1.0
dayfactor = 0.01
for i in range(365):
   if i % 7 in [6,0]:
       dayup = dayup*(1-dayfactor)
   else:
       dayup = dayup*(1+dayfactor)
print("工作日的力量:{:.2f} ".format(dayup))
 

 

天天向上的力量 第四问

 

#DayDayUpQ4.py
def dayUP(df):
    dayup = 1
    for i in range(365):
       if i % 7 in [6,0]:
           dayup = dayup*(1 - 0.01)
       else:
           dayup = dayup*(1 + df)
    return dayup
dayfactor = 0.01
while dayUP(dayfactor) < 37.78:
    dayfactor += 0.001
print("工作日的努力参数是:{:.3f} ".format(dayfactor))
 

文本进度条 简单的开始

 

#TextProBarV1.py
import time
scale = 10
print("------执行开始------")
for i in range(scale+1):
    a = '*' * i
    b = '.' * (scale - i)
    c = (i/scale)*100
    print("{:^3.0f}%[{}->{}]".format(c,a,b))
    time.sleep(0.1)
print("------执行结束------")
 

 

文本进度条 单行动态刷新

 

#TextProBarV2.py
import time
for i in range(101):
    print("\r{:3}%".format(i), end="")
    time.sleep(0.1)
 

 

文本进度条 实例完整效果

 

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

版本1

 

#CalBMIv1.py
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who = ""
if bmi < 18.5:
    who = "偏瘦"
elif 18.5 <= bmi < 25:
    who = "正常"
elif 25 <= bmi < 30:
    who = "偏胖"
else:
    who = "肥胖"
print("BMI 指标为:国际'{0}'".format(who))
 

 

版本2

 

#CalBMIv2.py
height, weight = eval(input("请输入身高(米)和体重\(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
nat = ""
if bmi < 18.5:
    nat = "偏瘦"
elif 18.5 <= bmi < 24:
    nat = "正常"
elif 24 <= bmi < 28:
    nat = "偏胖"
else:
    nat = "肥胖"
print("BMI 指标为:国内'{0}'".format(nat))
 

版本3

 

#CalBMIv3.py
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who, nat = "", ""
if bmi < 18.5:
    who, nat = "偏瘦", "偏瘦"
elif 18.5 <= bmi < 24:
    who, nat = "正常", "正常"
elif 24 <= bmi < 25:
    who, nat = "正常", "偏胖"
elif 25 <= bmi < 28:
    who, nat = "偏胖", "偏胖"
elif 28 <= bmi < 30:
    who, nat = "偏胖", "肥胖"
else:
    who, nat = "肥胖", "肥胖"
print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))
 

公式法

 

#CalPiV1.py
pi = 0
N = 100
for k in range(N):
    pi += 1/pow(16,k)*( \
              4/(8*k+1) - 2/(8*k+4) - \
              1/(8*k+5) - 1/(8*k+6) ) 
print("圆周率值是: {}".format(pi))
 

蒙特卡罗方法

 

#CalPiV2.py
from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter()
for i in range(1, DARTS+1):
    x, y = random(), random()
    dist = pow(x ** 2 + y ** 2, 0.5)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits/DARTS)
print("圆周率值是: {}".format(pi))
print("运行时间是: {:.5f}s".format(perf_counter() - start))
第五周  可变参数

 #一

def fact(n,*b):
    s = 1
    for i in range(1,n+1):
        s *= i
    for item in b:
        s *= item
    return s


print(fact(10,3,5,8))

#二 函数调用时,可以按照位置或名称方式传递,函数可以返回0个或多个结果
def fact(n,m=1):
    s = 1
    for i in range(1,n+1):
        s *= i
    return s//m,n,m

print(fact(10,5)) #以元组类型返回
print(fact(m=5,n=10)) #以元组类型返回

a,b,c = fact(10,5) #分别复制给变量,然后返回
print(a,b,c)
#三global
n,s = 10,100
def fact(n):
    global s
    for i in range(1,n+1):
        s *= i
    return s

print(fact(n),s)
#四
#局部变量为组合数据类型且未创建,等同于全局变量
ls = ["F",'f']
def func(a):
    ls.append(a)
    return
func('C')
print(ls)
#五
#创建局部变量
ls = ["F",'f']
def func(a):
    ls = [] #创建了局部变量,在函数运行后被释放了,所以函数的运行结果是['F', 'f']
    ls.append(a)
    return
func('C')
print(ls)
#六
#lambda
f = lambda x,y:x+y
print(f(10, 15))
#lambda接受没有参数的函数
f = lambda : "lambda函数"
print(f())
七段数码管版本一
#SevenDigitsDrawV1.py
import turtle
def drawLine(draw): #绘制单段数码管
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    turtle.right(90)
def drawDigit(digit): #根据数字绘制七段数码管
    drawLine(True) if digit in [2,3,4,5,6,7,8,9] 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() #为绘制后续数字确定位置
    turtle.fd(20) #为绘制后续数字确定位置
def drawDate(date): #获得要输出的数字
    for i in date:
        drawDigit(eval(i)) #通过eval()函数将数字变为整数
def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.bk(300) #turtle.fd(-300)
    turtle.pensize(5)
    drawDate('20181010')
    turtle.hideturtle()
    turtle.done()
main()

七段数码管版本二
#SevenDigitsDrawV2.py
import turtle,time
def drawGap(): #绘制数码管间隔
    turtle.penup()
    turtle.fd(5)
def drawLine(draw): #绘制单段数码管
    drawGap()
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    drawGap()
    turtle.right(90)

def drawDigit(digit): #根据数字绘制七段数码管
    drawLine(True) if digit in [2,3,4,5,6,7,8,9] 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() #为绘制后续数字确定位置
    turtle.fd(20) #为绘制后续数字确定位置
def drawDate(date):  #data为日期,格式为 '%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"))
        else:
            drawDigit(eval(i))
def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.bk(350) #turtle.fd(-300)
    turtle.pensize(5)
    # drawDate('2018-10=10+')
    drawDate(time.strftime('%Y-%m=%d+',time.gmtime()))
    turtle.hideturtle()
    turtle.done()
main()

第六周:基本统计值计算
#CalStatisticsV1.py
def getNum():
    nums = [] #获取用户不定长度的输入 
    iNumStr = input("请输入数字(回撤退出):")
    while iNumStr != "":
        nums.append(eval(iNumStr))
        iNumStr = input("请输入数字(回车退出):")
    return nums
def mean(numbers):  #计算平均值
    s = 0.0
    for num in numbers:
        s = s + num
    return s / len(numbers)
def dev(numbers,mean): #计算标准差
    sdev = 0.0
    for num in numbers:
        sdev += (num - mean) ** 2
    return pow(sdev / (len(numbers) - 1),0.5)
def median(numbers):  #计算中位数
    sorted(numbers)
    size = len(numbers)
    if size % 2 == 0:
        med = (numbers[size//2-1] + numbers[size//2])/2
    else:
        med = numbers[size//2]
    return med
n = getNum()
m = mean(n)
print("平均值:{},标准差:{:.2},中位数:{}.".format(m,dev(n,m),median(n)))

#Hamlet英文词频统计
#CalHamletV1.py
def getText():
    txt = open("hamlet.txt","r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_{|}~':
        txt = txt.replace(ch," ")
    return  txt

hamletTxt = getText() #对文件进行读取,并且对文本进行规划
words = hamletTxt.split() #.split()默认采用空格,将字符串中的信息进行分割,并且以列表形式返回给变量,words是一个列表类型,里面每个元素是一个空格分开的单词
counts = {} #一个单词和它出现的次数构成的一种映射,需要定义字典类型,来表达单词更出现频率之间的对应关系,定义空字典counts
for word in words: #逐一从words列表中取出元素,取出之后尝试下这个元素是否在counts中
    counts[word] = counts.get(word,0) + 1 #用get获取字典中每一个键对应的值,如果这个键不存在在字典中,我们给出默认值,counts.get(word,0),指的是用当前的某一个英文单词作为键索引字典,如果此英文单词在里面,就返回吃单词的次数,后面再加1,就说明这个单词又出现了一次,如果此单词不在字典中,就把它加到字典中,并且赋给当前的值为0,0加1是1,说明这个单词出现了一次,相当于在字典中新增了一个元素
#通过以上两行代码,就能够逐一遍历列表中的每个元素,并且用字典类型去记录每个元素出现的次数
items = list(counts.items()) #转换成列表类型
items.sort(key=lambda x:x[1],reverse=True) #用列表类型的sort方法排序,lambda参数用来指定在列表中使用哪一个多元选项的列作为排序列,默认的排序方法是从小到大,reverse=True返回的排序就是从大到小,排序之后的信息保存在items中,
for i in range(10): #items中的第一个元素就是出现次数最多的元素,用for语句将其中的前10个出现最多的单词以及它对应的次数打印出来
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))
《三国演义》人物出场统计(上)
#CalThreeKingdomsV1.py
import jieba
txt = open("threekingdoms.txt","r",encoding="utf-8").read()
words = jieba.lcut(txt) #用jieba.lcut()进行分词处理,形成列表类型的带有所有单词的列表叫做words
counts = {}
for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word,0) + 1
items = list(counts.items()) #转换为列表类型
items.sort(key=lambda x:x[1],reverse=True)
for i in range(15):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))
《三国演义》人物出场统计(下)
#CalThreeKingdomsV2.py
import jieba
txt = open("threekingdoms.txt","r",encoding="utf-8").read()
excludes = {"将军","却说","荆州","二人","不可","不能","如此"}
words = jieba.lcut(txt) #用jieba.lcut()进行分词处理,形成列表类型的带有所有单词的列表叫做words
counts = {}
for word in words:
    if len(word) == 1:
        continue
    elif word == "诸葛亮" or word == "孔明曰":
        rword = "孔明"
    elif word == "关公" or word == "云长":
        rword = "关羽"
    elif word == "玄德" or word == "玄德曰":
        rword = "刘备"
    elif word == "孟德" or word == "丞相":
        rword = "曹操"
    else:
        rword = word
    counts[rword] = counts.get(rword,0) + 1
for word in excludes:
    del counts[word]
items = list(counts.items()) #转换为列表类型
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
    word,count = items[i]
    print("{0:<10}{1:>5}".format(word,count))

文件的逐行操作
#逐行遍历文件
fname = input("请输入要打开的文件名称:")
fo = open(fname,"r") #fo是文件距离
for line in fo: #使用for in可以实现对文件(尤其是文本文件)逐行处理,此即实现了分行读入逐行处理
    print(line)
fo.close()

数据的文件写入
fo = open("output.txt","w+")
ls = ["中国","法国","美国"]
fo.writelines(ls) #写入一个字符串列表
fo.seek(0) #写入ls后将指针返回到文件的最开始
for line in fo:
    print(line)
fo.close()
第七周,自动轨迹绘制
#AutoTraceDraw.py
import turtle as t
t.title("自动轨迹绘制")
t.setup(800,600,0,0)
t.pencolor("red") #设置初始画笔颜色
t.pensize(5) #设置绘制画笔的粗细
#数据读取
datals = []
f = open("data.txt")
for line in f:
    line = line.replace("\n","") #使用.replace将第一行换行符"\n"转换为空字符串,
    # 去掉换行的信息,付给变量line,此时line存储的是我们定义的每一行数据接口的值,
    # 需要将数据接口的值分割处理并且提取其中的信息
    datals.append(list(map(eval,line.split(",")))) #用line.split指定","为分割符
    # 将这样的一个字符串分割成若干个字符串,所分割的依据就是",",能够生成一个列
    # 表,此列表中每一个元素是一段字符串,用","分割,map()函数的作用是将第一个
    # 参数的功能作用于每个元素,map()的第一个参数是一个函数的名字,第二个参数
    # 是一个迭代类型
f.close()
#自动绘制
for i in range(len(datals)):
    t.pencolor(datals[i][3],datals[i][4],datals[i][5])
    t.fd(datals[i][0]) #获取当前这一行中的第一个元素,表示行进的距离
    if datals[i][1]: #判断数据接口的第二列元素,1向右转,0向左转
        t.right(datals[i][2])  #datals[i][2]表示转向角度
    else:
        t.left(datals[i][2])
 #wordcloud应用实例
#1
import wordcloud
c = wordcloud.WordCloud()
c.generate("wordcloud by Python")
c.to_file("pywordcloud.png")

#2 
import wordcloud
txt = "life is short,you need python"
w = wordcloud.WordCloud( background_color = "white") #用wordcloud.WordCloud生成词云对象,给出参数background_color
w.generate(txt) #用.generate()方法将文本加载到对象中
w.to_file("pywcloud.png") #用to_file()方法将词云输出为png文件

#3

import jieba
import wordcloud
txt = "程序设计语言是计算机能够理解和\
识别用户操作意图的一种交互体系,它按照\
特定规则组织计算机指令,使计算机能够自\
动进行各种运算处理。"
w = wordcloud.WordCloud( width=1000,\
font_path="msyh.ttc",height=700)
w.generate(" ".join(jieba.lcut(txt))) #lcut生成一个列表
w.to_file("pywcloud.png")

#4
#GovRptWordCloudv1.py
import jieba
import wordcloud
f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")

t = f.read()
f.close()
ls = jieba.lcut(t)

txt = " ".join(ls)
w = wordcloud.WordCloud( \
width = 1000, height = 700,\
background_color = "white",
font_path = "msyh.ttc",max_words = 15 
)
w.generate(txt)
w.to_file("grwordcloud.png")

#5

#-*- coding:utf-8 -*-
#GovRptWorldCloudv1.py
import jieba
import wordcloud
f = open("关于实施乡村振兴战略的意见.txt","r",encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(font_path = "msyh.ttc",\
width = 1000,height = 700,background_color = "white",\
max_words = 15 )
w.generate(txt) #加载txt
w.to_file("grwordcloud.png") #生成执行文件

#6

 

#GovRptWordCloudv1.py
import jieba
import wordcloud
from scipy.misc import imread #引入一个库scipy
mask = imread("fivestart.png") #imread()方法能够读取一个图片文件,
#并且生成一个图片文件表达的内容变量
f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")

t = f.read()
f.close()
ls = jieba.lcut(t)

txt = " ".join(ls)
w = wordcloud.WordCloud( \
width = 1000, height = 700,\
background_color = "white",
font_path = "msyh.ttc",mask = mask
)
w.generate(txt)
w.to_file("grwordcloud.png")

 #7

#-*- coding:utf-8 -*-
#GovRptWorldCloudv1.py
import jieba
import wordcloud
from scipy.misc import imread
mask = imread("fivestart.png")
f = open("关于实施乡村振兴战略的意见.txt","r",encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(font_path = "msyh.ttc",\
width = 1000,height = 700,background_color = "white",\
mask = mask )
w.generate(txt) #加载txt
w.to_file("grwordcloud.png") #生成执行文件

#8

#GovRptWordCloudv1.py
import jieba
import wordcloud
from scipy.misc import imread #引入一个库scipy
mask = imread("chinamap.jpg") #imread()方法能够读取一个图片文件,
#并且生成一个图片文件表达的内容变量
f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")

t = f.read()
f.close()
ls = jieba.lcut(t)

txt = " ".join(ls)
w = wordcloud.WordCloud( \
width = 1000, height = 700,\
background_color = "white",
font_path = "msyh.ttc",mask = mask
)
w.generate(txt)
w.to_file("grwordcloud.png")

第八周 体育竞技分析

 

#MatchAnalysis.py
# 框架及步骤
# 1.打印程序的介绍性信息式                  -printInfo()
# 2.获得程序运行参数:proA,proB,n            -getInputs()
# 3,利用球员A和B的能力值,模拟n局比赛       -simNGames()
# 4.输出球员A和B获胜比赛的场次及概率        -printSummary()
from random import random
# 1
def printIntro():
    print("这个程序模拟两个选手A和B的某种竞技比赛")
    print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
# 2
def getInputs():
    a = eval(input("请输入选手A的能力值(0-1):"))
    b = eval(input("请输入选手B的能力值(0-1):"))
    n = eval(input("模拟比赛的场次:"))
    return a, b, n

def simOneGame(probA,probB):
    scoreA,scoreB = 0,0
    serving = "A"
    while not gameOver(scoreA,scoreB):
        if serving == "A":    #表示选手A开始发球
            if random() < probA: #用random()生成一个随机变量
                scoreA += 1
            else:
                serving="B"
        else:
            if random() < probB: #用random()生成一个随机变量
                scoreB += 1
            else:
                serving="A"
    return scoreA,scoreB
def gameOver(a,b):
    return a==15 or b==15

def simNGames(n,probA,probB):
    winsA,winsB = 0,0
    for i in range(n):
        scoreA,scoreB = simOneGame(probA,probB)
        if scoreA > scoreB:
            winsA += 1 #将A的获胜次数加1
        else:
            winsB += 1
    return winsA,winsB

def printSummary(winsA, winsB): #根据A,B获胜场次将相关信息和概率打印出来
    n = winsA + winsB
    print("竞技分析开始,共模拟{}场比赛".format(n))
    print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA, winsA / n))
    print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB / n))
def main():
    printIntro()
    probA, probB, n = getInputs()  # 获得A,B选手能力值以及次数n
    winsA, winsB = simNGames(n, probA, probB)  # 用probA,probB获得比赛场次
    printSummary(winsA, winsB)
main()
 第九周

#HollandRadarDraw霍兰德人格分析雷达图
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei'
radar_labels = np.array(['研究型(I)','艺术型(A)','社会型(S)',\
                         '企业型(E)','常规型(C)','现实型(R)']) #雷达标签
nAttr = 6
data = np.array([[0.40, 0.32, 0.35, 0.30, 0.30, 0.88],
                 [0.85, 0.35, 0.30, 0.40, 0.40, 0.30],
                 [0.43, 0.89, 0.30, 0.28, 0.22, 0.30],
                 [0.30, 0.25, 0.48, 0.85, 0.45, 0.40],
                 [0.20, 0.38, 0.87, 0.45, 0.32, 0.28],
                 [0.34, 0.31, 0.38, 0.40, 0.92, 0.28]]) #数据值
data_labels = ('艺术家', '实验员', '工程师', '推销员', '社会工作者','记事员')
angles = np.linspace(0, 2*np.pi, nAttr, endpoint=False)
data = np.concatenate((data, [data[0]]))
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure(facecolor="white")
plt.subplot(111, polar=True)
plt.plot(angles,data,'o-', linewidth=1, alpha=0.2)
plt.fill(angles,data, alpha=0.25)
plt.thetagrids(angles*180/np.pi, radar_labels,frac = 1.2)
plt.figtext(0.52, 0.95, '霍兰德人格分析', ha='center', size=20)
legend = plt.legend(data_labels, loc=(0.94, 0.80), labelspacing=0.1)
plt.setp(legend.get_texts(), fontsize='large')
plt.grid(True)
plt.savefig('holland_radar.jpg')
plt.show()
#RoseDraw.py 绘制最美的玫瑰花送给心爱的人儿
import turtle as t
# 定义一个曲线绘制函数
def DegreeCurve(n, r, d=1):
    for i in range(n):
        t.left(d)
        t.circle(r, abs(d))
# 初始位置设定
s = 0.2 # size
t.setup(450*5*s, 750*5*s)
t.pencolor("black")
t.fillcolor("red")
t.speed(100)
t.penup()
t.goto(0, 900*s)
t.pendown()
# 绘制花朵形状
t.begin_fill()
t.circle(200*s,30)
DegreeCurve(60, 50*s)
t.circle(200*s,30)
DegreeCurve(4, 100*s)
t.circle(200*s,50)
DegreeCurve(50, 50*s)
t.circle(350*s,65)
DegreeCurve(40, 70*s)
t.circle(150*s,50)
DegreeCurve(20, 50*s, -1)
t.circle(400*s,60)
DegreeCurve(18, 50*s)
t.fd(250*s)
t.right(150)
t.circle(-500*s,12)
t.left(140)
t.circle(550*s,110)
t.left(27)
t.circle(650*s,100)
t.left(130)
t.circle(-300*s,20)
t.right(123)
t.circle(220*s,57)
t.end_fill()
# 绘制花枝形状
t.left(120)
t.fd(280*s)
t.left(115)
t.circle(300*s,33)
t.left(180)
t.circle(-300*s,33)
DegreeCurve(70, 225*s, -1)
t.circle(350*s,104)
t.left(90)
t.circle(200*s,105)
t.circle(-500*s,63)
t.penup()
t.goto(170*s,-30*s)
t.pendown()
t.left(160)
DegreeCurve(20, 2500*s)
DegreeCurve(220, 250*s, -1)
# 绘制一个绿色叶子
t.fillcolor('green')
t.penup()
t.goto(670*s,-180*s)
t.pendown()
t.right(140)
t.begin_fill()
t.circle(300*s,120)
t.left(60)
t.circle(300*s,120)
t.end_fill()
t.penup()
t.goto(180*s,-550*s)
t.pendown()
t.right(85)
t.circle(600*s,40)
# 绘制另一个绿色叶子
t.penup()
t.goto(-150*s,-1000*s)
t.pendown()
t.begin_fill()
t.rt(120)
t.circle(300*s,115)
t.left(75)
t.circle(300*s,100)
t.end_fill()
t.penup()
t.goto(430*s,-1070*s)
t.pendown()
t.right(30)
t.circle(-600*s,35)
t.done()

 

你可能感兴趣的:(python入门之路)