中国大学 MOOC 课程 《Python 语言程序设计》 课后练习(第 2 周)

中国大学 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)

“`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值