中国大学 MOOC 课程《Python 语言程序设计》课后练习(第 2 周)
1、蟒蛇程序绘制:
import turtle
def drawSnake(rad,angle,len,neckrad):
for i in range(len):
turtle.circle(rad,angle) #朝左的半径,弧度值
turtle.circle(-rad,angle)
turtle.circle(rad,angle/2)
turtle.fd(rad)
turtle.circle(neckrad+1,180) #弧度值设为180度
turtle.fd(rad*2/3)
def main():
turtle.setup(1300,800,0,0) #设置画图窗口大小
pythonsize=3
turtle.pensize(pythonsize)
turtle.pencolor("blue")
turtle.seth(-40) #初始画笔的角度
drawSnake(40,80,5,pythonsize/2)
main()
2、eval函数
功能:将字符串str当成有效的表达式来求值并返回计算结果。
语法: eval(source[, globals[, locals]]) -> value
参数:
source:一个Python表达式或函数compile()返回的代码对象
globals:可选。必须是dictionary
locals:可选。任意map对象
可以把list,tuple,dict和string相互转化。
#################################################
字符串转换成列表
>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>>type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> type(b)
<type 'list'>
#################################################
字符串转换成字典
>>> a = "{1: 'a', 2: 'b'}"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
{1: 'a', 2: 'b'}
>>> type(b)
<type 'dict'>
#################################################
字符串转换成元组
>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
>>> type(b)
<type 'tuple'>
3、绘制彩色蟒蛇
import turtle
import random
pencolors=['red','blue','yellow','black']
def drawSnake(rad,angle,len,neckrad):
for i in range(len):
turtle.circle(rad,angle)
turtle.circle(-rad,angle)
pencolor()
turtle.circle(rad,angle/2)
pencolor()
turtle.fd(rad)
turtle.circle(neckrad+1,180)
pencolor()
turtle.fd(rad*2/3)
def main():
turtle.setup(1300,800,0,0)
pythonsize=3
turtle.pensize(pythonsize)
pencolor()
turtle.seth(-40)
drawSnake(40,80,5,pythonsize/2)
def pencolor():
turtle.pencolor(pencolors[random.randint(0,3)])
main()
固定不同颜色:
import turtle
import random
pencolors=[‘red’,’blue’,’yellow’,’black’]
def drawSnake(rad,angle,len,neckrad):
turtle.pencolor(pencolors[3])
for i in range(len):
turtle.circle(rad,angle)
turtle.circle(-rad,angle)
turtle.pencolor(pencolors[1])
turtle.circle(rad,angle/2)
turtle.pencolor(pencolors[0])
turtle.fd(rad)
turtle.circle(neckrad+1,180)
turtle.fd(rad*2/3)
def main():
turtle.setup(1300,800,0,0)
pythonsize=30
turtle.pensize(pythonsize)
turtle.seth(-40)
drawSnake(40,80,5,pythonsize/2)
main()
4、蟒蛇绘制
5、绘制等边三角形
import turtle
for i in range(3):
turtle.fd(50)
turtle.left(120)
“`