第二章 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
获得一些建议
相关文章推荐
- Python基础——准备工作
- 判断一个数是不是3的幂——Power of three?
- python学习笔记(arange函数与linspace函数)
- python eval()
- python中如果函数后面有多于一个括号是怎么回事?
- 第三节,入门知识和windows系统安装python环境
- Python实战_0_第一周_第一节练习项目:动手做自己的网页
- python添加django插件
- Python:递归和装饰器
- Guido von Rossum - i wrote python
- Python六大开源框架对比:Web2py略胜一筹
- Python matplotlib pyplot中title() xlabel() ylabel()无法显示在中文(方框乱码)的解决办法
- python函数中参数是如何传递的?
- python对列表int的排序及斐波那契数列第四讲(4)
- python pip
- Python安装模块出错(ImportError: No module named setuptools)解决方法
- python中的os模块
- Python list index method
- python写用户登录程序(继续更新中)第四讲(3)
- Python HTML操作(HTMLParser)