您的位置:首页 > 编程语言 > Python开发

第二章 Python简介

2016-05-14 14:51 495 查看
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">为了督促自己学习,我将把自己学习树莓派Python编程的过程中的主要内容以博客的形式展现给大家,本篇博文及后续博文中大部分源码参考自《树莓派Python编程指南》这本书,有意购买者请支持正版,谢谢。</span>


2.1使用turtles绘画

</pre><pre code_snippet_id="1683147" snippet_file_name="blog_20160514_3_3131072" name="code" class="python"><pre name="code" class="python">import turtle    #导入turtle模块
import time      #导入time模块

boxsize = 200;   #变量定义
caught= False
score = 0

#functions that are called on keypresses
def up():
mouse.forward(10)
checkbound()

def left():
mouse.left(45)

def right():
mouse.right(45)

def back():
mouse.backward(10)
checkbound()

def quitTurtles():
window.bye()

#stop the mouse from leabing the square set by box size
def checkbound():
global boxsize    #在Python中,函数无法读取定义在函数外面的变量,这一样告诉Python,
#我们将在本函数中使用变量boxsize,而该变量实在函数外部定义的,
if mouse.xcor() > boxsize:
mouse.goto(boxsize, mouse.ycor())
if mouse.xcor() < -boxsize:
mouse.goto(-boxsize, mouse.ycor())
if mouse.ycor() > boxsize:
mouse.goto(mouse.xcor(), boxsize)
if mouse.ycor() < -boxsize:
mouse.goto(mouse.xcor(), -boxsize)

#set up screen
window = turtle.Screen()
mouse = turtle.Turtle()
cat = turtle.Turtle()
mouse.penup()
mouse.penup()
mouse.goto(100,100)

#add key listeners 监听按键:上、下、左、右、ESC
window.onkeypress(up, "Up")
window.onkeypress(left, "Left")
window.onkeypress(right, "Right")
window.onkeypress(back, "Down")
window.onkeypress(quitTurtles, "Escape")

difficulty = window.numinput("Diffculty",
"Enter a diffculty from easy (1), for hand (5) ",
minval=1, maxval=5)

window.listen()
#main loop
#note how it changes with difficulty
while not caught:
cat.setheading(cat.towards(mouse))  #调整cat的角度朝向mouse
cat.forward(8 + difficulty)         #向前移动指定的距离
score = score + 1                   #分数+1
if cat.distance(mouse) < 5:         #如果距离小于5
caught = True
time.sleep(0.2-(0.01*difficulty))   #难度等级越高,猫的速度越快
window.textinput("GAME OVER", "Well done. You scored:"+ str(score*difficulty))
window.bye()






小结:

1、Python程序有一些列命令组成并从上到下执行

2、可以通过循环和if语句控制程序的执行顺序

3、不必事必躬亲,通过导入模块,使用模块中的方法可以完成许多工作

4、函数可以帮助重用代码,也可以使程序变得易于理解和维护

5、变量可以存储信息以便后面使用

最后:

可以在Python解释器中输入:

>>> import this

获得一些建议
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: