Arcade 游戏编程教程(一)
一、开始之前…
这一介绍性章节有两个部分:
- 设置您的计算机来编写游戏。
- 技术领域的工作和职业前景。
安装和启动 Python
要开始,需要安装两个程序:Python 和 Pygame。Python 是我们将用来编程的计算机语言,Pygame 是一个命令库,它将帮助编写游戏变得更容易。
Windows 安装
如果您使用的计算机已经安装了 Python 和 Pygame,您可以跳过这一步。但是如果你想在自己的 Windows 电脑上设置 Python 和 Pygame,也不用担心。这很容易。
Run the Python installer downloaded from http://ProgramArcadeGames.com/python-3.4.3.msi Run the Pygame installer downloaded from http://ProgramArcadeGames.com/pygame-1.9.2a0.win32-py3.4.msi
一旦安装好所有的东西,通过选择集成开发环境(IDLE)启动 Python,如图所示。
启动 Python
上面提供的文件来自 http://www.python.org/download/ 的 Python 下载页面,Pygame 文件最初来自 https://bitbucket.org/pygame/pygame/downloads 。
Note
Python 和 Pygame 有很多版本。获得正确的版本并让它们一起工作可能会很复杂。我推荐使用 ProgramArcadeGames.com 上的链接,而不是从 Python 和 Pygame 网站下载。
如果你必须使用与这里所列不同的 Python 版本,可以在这个网站找到匹配的 Pygame 版本: www.lfd.uci.edu/∼gohlke/pythonlibs/#pygame 。
Mac 安装
Mac 的安装有点复杂,但还不算太糟。以下是步骤。
Open up a terminal window. Click on “Finder” then “Applications” and then open “Utilities.”
Starting a terminal window Double-click on “Terminal.”
Starting a terminal window We can issue commands to the Mac in the old-school style by typing them rather than pointing and clicking. We are going to start by typing in a command you probably don’t have yet. This command is gcc. Type this and hit the Enter key. Your Mac will recognize that you don’t have this command and offer to install it for you. Go ahead and do this. (If instead it says error: no input files you already have gcc, so go on to the next step.)
Starting a terminal window Install XQuartz from: http://xquartz.macosforge.org . Line by line, copy and paste the following items into your terminal window: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/ master/install)" sudo brew doctor brew update brew install python3 brew install sdl sdl_image sdl_mixer sdl_ttf portmidi mercurial If you want support for MP3s and movies, you can try adding smpeg. I’ve found support for this to be kind of spotty, so my recommendation is to skip this and use Ogg Vorbis files instead. But if you’d like to try, use these commands: brew install --HEAD https://raw.github.com/Homebrew/homebrew- headonly/master/smpeg.rb Now you have all the supporting libraries. Let’s finally install Pygame. Replace YourName with your account name. If you don’t know what your account name is, type ls /Users to see all the user accounts on your computer. cd /Users/YourName/Downloads hg clone https://bitbucket.org/pygame/pygame cd pygame cd src pip3 install /Users/YourName/Downloads/pygame
此时,Pygame 和 Python 应该已经在您的系统上启动并运行了。Python 没有提供编辑文件的方法,所以你需要下载一个 IDE,比如 Wing IDE ( http://wingware.com/downloads )或者 PyCharm ( https://www.jetbrains.com/pycharm/download/ ),或者其他编辑器。
Unix 安装
Unix 和类似 Unix 的发行版可能会附带一个 Pygame 包,或者能够轻松获得一个包。如果你想从源代码编译,这是我在 Linux Mint 上用过的( http://www.linuxmint.com/ ):
# Load required packages
sudo apt-get install mercurial libsdl1.2-dev
sudo apt-get install libasound2-doc libglib2.0-doc python3-dev
sudo apt-get install libsdl-ttf2.0-dev libsdl-image1.2-dev
sudo apt-get install libsdl-mixer1.2-dev libportmidi-dev
sudo apt-get install libavformat-dev libswscale-dev
sudo apt-get install libfreetype6-dev
sudo apt-get install libsmpeg-dev
# Use mercurial to clone current code
hg clone https://bitbucket.org/pygame/pygame
# Build and install
cd pygame
sudo python3 setup.py
UNIX 平台上最大的风险是您的默认 Python 版本可能是 2.x 系列,并且该代码不能与本书中的代码示例一起工作。确保您已经并且正在使用 Python 3.x。
可选 Wing IDE
Python 附带了一个编辑器和一个开发代码的环境。不幸的是,它不是很好。使用 Python 的默认编辑器时,可能会遇到以下两个问题:
问题 1。当处理多个文件时,很难跟踪所有打开的文件。运行程序前很容易忘记保存文件。当这种情况发生时,程序用保存的旧代码而不是新代码运行。这就很混乱了。
问题 2。如果绘制图形的程序中出现错误,Python 程序将会崩溃并挂起。一旦程序崩溃,就很难关闭。描述崩溃原因的错误消息通常被隐藏起来,很难找到。见下图。
Python 程序在空闲时挂起
Wing 编辑器通过为每个文件使用一个带选项卡的编辑器来解决问题 1。它还会提示在运行程序之前保存所有文件。在 Wing 调试器下运行的程序不会像问题 2 中描述的那样挂起;相反,编辑器会立即将用户带到导致错误的代码行。见下图。
Python 程序挂在 Wing IDE 中
因此,尽管这是第三个需要安装的东西,我还是推荐使用 Wing 编辑器。有一个免费版本叫做 wingware.com/downloads/wingide-101/ 的 Wing IDE 101。
不需要商业版附带的那些花里胡哨的东西,但是它们很好。当你开始输入变量名时,这个程序通常会自动填充变量名来帮助你。如果你有额外的钱,并想节省时间,你可能想拿起商业版本。
在网站上的视频中,我要么使用默认的 Python 编辑器,要么使用 Wing 编辑器。也可以使用许多其他编辑器:
- PyCharm (
http://www.jetbrains.com/pycharm/) - 崇高(
http://www.sublimetext.com/) - PyDev on Eclipse (
http://pydev.org/) - 科莫多编辑 (
http://www.activestate.com/komodo-edit) - 记事本++ (
http://notepad-plus-plus.org/)
在一些开发者中,讨论“哪个是最好的编辑器?”类似于让一群人聚在一起讨论“哪个是最好的宗教?”。最好是挑自己喜欢的,然后和其他人回避这个话题。
查看文件扩展名
更改您的 windows 配置以显示文件扩展名是一个好主意。一个文件通常有一个类似于Book report.docx的名字,其中.docx告诉计算机它是一个微软 Word 兼容的文档。默认情况下,如果安装了处理扩展的程序,Windows 会隐藏.docx扩展名。如果您正在编程,文件名的这种隐藏部分可能会很烦人。
对于 Windows 7,要显示文件扩展名,请打开计算机的控制面板。找到“文件夹选项”的选项单击“查看”选项卡,然后取消选择“隐藏已知文件类型的扩展名”选项
对于 Windows 8,按 Windows-E 键打开文件浏览器。然后点击“查看”标签,并确保“文件扩展名”已被选中。
学习制作游戏并获得报酬
当你开始学习编程时,你可能很快会发现它看起来像工作。我们都知道我们宁愿翘班去魔兽世界或 Eve Online 或其他游戏中淘金,对吗?那么为什么要学习编程呢?一个人从中能得到什么?
成袋的钱
学习如何制作游戏并获得报酬?好吧,我不会付钱给你,但是如果你学编程,有很多人会付钱给你。以下是如何获利:
Learn to program games. Have fun making your own games. Select a favorite job offer. Profit.
听着,不是吗???在这个计划里!
好好想想。你可以玩游戏,但任何人都可以这样做。仔细想想,在电子游戏上表现出色真的不算是人生中的一大成就。或者你可以学习创造游戏。人们关心这个。
从本书中获得最大收益
伟大的篮球运动员练习。伟大的程序员也是如此。
想让你在这里的时间变得有价值吗?回答章节问题!不要跳过它们。他们是理解材料所必需的。
做练习!这就更重要了。仅仅通过阅读材料来学习和仅仅通过阅读一本书来成为一名专业的篮球运动员是一样有用的。
练习!你可能会看到其他不需要练习的人。这不公平。或者,你可能比其他人更聪明,他们开始做得比你好,因为他们努力了,而你没有。这也不公平。这就是生活。习惯吧。练习。
你在课堂上读这本书吗?太好了。你知道你可以节省时间,从网上复制答案和练习吗?你也可以给自己买一张健身房会员卡,让别人帮你健身。这也说得通。
说真的,你到底在想什么抄袭别人?如果你不想做这份工作,现在就停止阅读,开始填写麦当劳的申请表。
不做作业是学不到的。做阅读。做练习。
发送反馈
如果你发现书中有任何错误或遗漏,请发电子邮件给我。我希望这是最好的资源。
保罗·文森特·克雷文博士
计算机科学系系主任
美国爱荷华州印第安诺拉辛普森学院,邮编:50125
保罗·克拉文@simpson.edu
二、创建自定义计算器
使用 Python 可以做的最简单的事情之一就是将它用作一个奇特的计算器。等等,计算器不是游戏。为什么我们要谈论计算器?乏味的....
嘿,要计算物体掉落,子弹乱飞,高分,我们需要计算。此外,任何真正的极客都会认为计算器是一个玩具,而不是一个酷刑设备!让我们用计算器开始我们的游戏教育。别担心,我们会在第六章前开始制图。
一个简单的计算器程序可以用来向用户询问信息,然后计算一些无聊的事情,如抵押贷款,或者更令人兴奋的事情,如泥球抛向空中的轨迹。
下图显示了一个计算动能的示例程序,这是我们在游戏物理引擎中可能需要做的事情。
用 Python 计算动能
作为一个程序来做这件事最大的好处是能够隐藏方程式的复杂性。用户需要做的只是提供信息,他或她就能以一种易于理解的格式得到结果。任何类似的定制计算器都可以在智能手机上运行,让人们可以在旅途中轻松完成计算。
印刷
打印文本
一个程序如何把东西打印到屏幕上?代码很简单。只需要一行代码:
print("Hello World.")
这个程序将“Hello World”打印到屏幕上。继续前进,进入空闲提示,看看它是如何工作的。尝试打印其他单词和短语。计算机会很乐意打印出你喜欢的任何东西,不管是真是假。
其他计算机编程语言的“Hello World”程序是什么样子的?查看维基百科。他们保存了一套用多种不同的计算机编程语言编写的“Hello World”程序: http://en.wikipedia.org/wiki/Hello_world_program_examples 。
看到有多少种不同的计算机语言是很有趣的。你可以通过“Hello World”程序的简单程度来了解一门语言有多复杂。
记住,Python 中的打印命令很简单。用print就行了。在print命令之后是一组括号()。这些括号内是应该打印到屏幕上的内容。使用括号向函数传递信息是数学和计算机语言中的标准做法。
学数学的学生学习使用圆括号来计算像这样的表达式。和是函数。传递给这些函数的数据在括号内。在我们的例子中,不同的是传递的信息是文本。
请注意,要打印的文本周围有双引号。如果打印语句在文本周围有引号,计算机将按原样打印出来。例如,该程序将打印 2+3:
print("2 + 3")
打印表达式的结果
下一个程序在附近没有引号,计算机将把它作为一个数学表达式来计算。它将打印 5 而不是 2+3。
print(2 + 3)
下面的代码将生成一个错误,因为计算机将尝试将“Hello World”作为一个数学表达式来计算,但这根本行不通:
print(Hello World)
上面的代码会打印出一个错误SyntaxError: invalid syntax,,这是计算机的说法,表示不知道“Hello”和“World”是什么意思。
另外,请记住,这是单引号:’,这是双引号:"。如果我要求一个双引号,这是一个常见的错误,写"",实际上是一个双,双引号。
打印多个项目
一条print语句可以一次输出多项内容,每项内容用逗号分隔。例如,这段代码将打印出Your new score is 1040:
print("Your new score is", 1030 + 10)
下一行代码将打印出Your new score is 1030+10。这些数字没有加在一起,因为它们在引号内。引号内的任何内容,计算机都视为文本。计算机之外的任何东西都认为是数学语句或计算机代码。
print("Your new score is", "1030 + 10")
逗号在引号内还是引号外?
下一个代码示例根本不工作。这是因为引号和 1030+10 之间没有逗号分隔文本。起初,可能看起来有一个逗号,但逗号在引号内。分隔要打印的术语的逗号必须在引号之外。如果程序员想要打印一个逗号,那么它必须在引号内:
print("Your new score is," 1030 + 10)
下一个例子是可行的,因为有一个逗号分隔两个术语。它打印:
Your new score is, 1040
注意,只有一个逗号打印出来。引号外的逗号分隔术语,引号内的逗号打印出来。打印第一个逗号;第二个用于分隔术语。
print("Your new score is,", 1030 + 10)
转义码
如果用引号来告诉计算机你想打印的文本串的开始和结束,程序如何打印出一组双引号呢?例如:
print("I want to print a double quote " for some reason.")
这个代码不起作用。计算机查看字符串中间的引号,并认为这是文本的结尾。然后它不知道如何处理命令for some reason,引号和字符串的结尾会让计算机更加困惑。
有必要告诉计算机,我们想把中间的双引号当作文本,而不是字符串结尾的引号。这很简单:只要在引号前加上一个反斜杠,告诉计算机它是字符串的一部分,而不是终止字符串的字符。例如:
print("I want to print a double quote \" for some reason.")
这两个字符\"的组合称为转义码。几乎每种语言都有。因为反斜杠被用作转义码的一部分,所以反斜杠本身必须被转义。例如,以下代码无法正常工作:
print("The file is stored in C:\new folder")
为什么?因为\n是转义码。要打印反斜杠,必须像这样对它进行转义:
print("The file is stored in C:\\new folder")
还有一些其他重要的转义码需要知道。下面是重要转义码的表格:
| 转义码 | 描述 | | --- | --- | | \' | 单引号 | | \" | 双引号 | | \t | 标签 | | \r | 回车(向左移动) | | \n | 换行(向下移动) |什么是回车,什么是换行?试试这个例子:
print("This\nis\nmy\nsample.")
该命令的输出是:
This
is
my
sample.
\n是一个换行符号。它将光标移动到计算机将向下打印一行文本的位置。计算机将所有文本存储在一个很长的行中。由于放置了\n字符,它知道在不同的行上显示文本。
更复杂的是,不同的操作系统对行尾有不同的标准。
| 转义码 | 描述 | | --- | --- | | `\r\n` | CR+LF:微软视窗 | | `\n` | LF:基于 UNIX 的系统,以及更新的 MAC | | `\r` | CR:基于 Mac 的旧系统 |通常你的文本编辑器会帮你处理这个问题。Microsoft Notepad 则不然,在 Notepad 中打开的 UNIX 文件看起来很糟糕,因为行尾根本不显示,或者显示为黑框。每个程序员都应该在他们的电脑上安装一个好的文本编辑器。我推荐 Sublime ( www.sublimetext.com/ )或者 Notepad++ ( http://notepad-plus-plus.org/ )。
评论
评论很重要(即使电脑忽略了)!
有时代码需要向阅读它的人做一些额外的解释。为此,我们向代码中添加注释。注释是给阅读代码的人看的,而不是给计算机看的。
创建评论有两种方法。第一种是使用#符号。计算机将忽略 Python 程序中出现在#之后的任何文本。例如:
# This is a comment, it begins with a # sign
# and the computer will ignore it.
print("This is not a comment, the computer will")
print("run this and print it out.")
如果一个程序在引号之间有一个#符号,它不会被当作一个注释。程序员可以通过在一行代码前面放一个#符号来禁用它。也可以在行尾添加注释。
print("A # sign between quotes is not a comment.")
# print("This is a comment, even if it is computer code.")
print("Hi") # This is an end-of-line comment
可以在一行中使用三个单引号来分隔注释,从而注释掉多行代码。
print("Hi")
’’’
This is
a
multi
line
comment. Nothing
Will run in between these quotes.
print("There")
’’’
print("Done")
大多数专业的 Python 程序员只会对叫做 docstrings 的东西使用这种类型的多行注释。Docstrings 允许文档与代码一起编写,然后自动提取到打印文档、网站和集成开发环境(ide)中。对于一般的注释,#标签效果最好。
即使你是唯一一个阅读你写的代码的人,注释也可以帮助节省时间。添加“处理外星人炸弹”的注释可以让你快速记住那段代码做了什么,而不必阅读和破译它。
赋值运算符
我们如何在游戏中存储分数?或者跟踪敌人的健康状况?我们需要做的是赋值操作符。
运算符是类似于+或-的符号。赋值运算符是=符号。它将一个值存储到一个变量中,供以后使用。下面的代码将把 10 赋给变量x,然后打印存储在 x 中的值。
看看下面的例子。
# Create a variable x
# Store the value 10 into it.
x = 10
# This prints the value stored in x.
print(x)
# This prints the letter x, but not the value in x
print("x")
# This prints "x= 10"
print("x=", x)
变量在引号之外,而不是在里面。
Note
上面的清单还展示了打印内部引号x和外部引号x的区别。如果一个x在引号内,那么计算机打印x。如果x在引号之外,计算机将打印x的值。对于学习编程的人来说,对“引号内还是引号外”这个问题感到困惑是很常见的。
赋值语句(使用=操作符的一行代码)不同于你在数学中学到的代数等式。不要认为它们是一样的。赋值运算符的左侧必须正好有一个变量。那里可能没有别的东西。
等号/赋值运算符的右边是一个表达式。表达式是计算结果为值的任何东西。检查下面的代码。
x = x + 1
上面的代码显然不可能是代数等式。但是它对计算机是有效的,因为它是一个赋值语句。数学方程不同于赋值语句,即使它们有变量、数字和等号。
语句上面的代码获取当前值x,加 1,并将结果存储回x。
扩展我们的示例,下面的语句将打印数字 6。
x = 5
x = x + 1
print(x)
语句按顺序运行。计算机不会向前看。在下面的代码中,计算机将在第 2 行打印出 5,然后第 4 行打印出 6。这是因为在第 2 行,给 x 加 1 的代码还没有运行。
x = 5
print(x) # Prints 5
x = x + 1
print(x) # Prints 6
下一个语句是有效的,将运行,但它是无意义的。计算机会给 x 加 1,但结果不会被存储或打印出来。
x + 1
下面的代码将打印 5 而不是 6,因为程序员忘记将x + 1的结果存储回变量x中。
x = 5
x + 1
print(x)
下面的语句无效,因为等号的左边不仅仅是一个变量:
x + 1 = x
Python 还有其他类型的赋值操作符。它们允许程序员很容易地修改变量。例如:
x += 1
上面的语句相当于编写下面的代码:
x = x + 1
还有用于加法、减法、乘法和除法的赋值运算符。
变量
变量以小写字母开头。
变量应该以小写字母开头。变量可以以大写字母或下划线开头,但这是特殊情况,不应该在正常情况下使用。在第一个小写字母之后,变量可以包括大写和小写字母,以及数字和下划线。变量不能包含空格。
变量区分大小写。如果程序员没有预料到,这可能会令人困惑。在下面的代码中,输出将是 6 而不是 5,因为有两个不同的变量,x和X。
x = 6
X = 5
print(x)
Python 的官方风格指南(是的,程序员真的写了一本关于风格的书)说 Python 中的多字变量名应该用下划线隔开。比如用hair_style,不用hairStyle。就我个人而言,我并不太关心这个规则,因为我们引入的下一种语言 Java 有完全相反的风格规则。我曾经尝试在这样的章节中教授 Java 风格的规则,但是后来我开始收到 Python 爱好者的恐吓信。这些人来到我的网站,对我糟糕的风格感到震惊。
琼·里弗斯没有这些人,所以我放弃了,现在尝试使用适当的风格指南。
以下是一些可以使用和不可以使用的变量名示例:
| 合法变量名 | 非法变量名 | 合法,但不正当 | | --- | --- | --- | | `first_name` | `first name` | `FirstName` | | `distance` | `9ds` | `firstName` | | `ds9` | `%correct` | `X` |只有在变量值永远不会改变的情况下,才允许使用像MAX_SPEED这样的大写变量名。不是可变的变量叫做常数。
经营者
对于更复杂的数学运算,可以使用常见的数学运算符。还有一些不常见的:
| 操作员 | 操作 | 示例方程 | 示例代码 | | --- | --- | --- | --- | | + | 添加 | 3 + 2 | a = 3 + 2 | | - | 减法 | 3 - 2$ | a = 3 - 2 | | * | 增加 | 3′2 | a = 3 * 2 | | / | 分开 |  | a = 10 / 2 | | // | 楼层划分 | 不适用的 | a = 10 // 3 | | ** | 力量 | 2 3 | a = 2 ** 3 | | % | 系数 | 不适用的 | a = 8 % 3 |地板除法总是将答案四舍五入到最接近的整数。例如,11//2将是 5,而不是 5.5,99//100将等于 0。
在 Python 中,并置乘法不起作用。下面两行代码将不起作用:
# These do not work
x = 5y
x = 5(3/2)
有必要使用乘法运算符来使这些代码行工作:
# These do work
x = 5 * y
x = 5 * (3 / 2)
运算符间距
运算符前后可以有任意数量的空格,计算机可以很好地理解。例如,这三行中的每一行都是等价的:
x=5*(3/2)
x = 5 * (3 / 2)
x =5 *( 3/ 2)
Python 的官方风格指南说每个操作符前后都应该有一个空格。(你一直很想知道,对吧?好了,python 代码的官方风格指南叫做 PEP-8 ( http://www.python.org/dev/peps/pep-0008/ )。更多精彩请查阅)。在上面的三行代码中,最有风格的是第 2 行。
操作顺序
Python 将使用标准数学表达式中预期的相同运算顺序来计算表达式。例如,该等式不能正确计算平均值:
average = 90 + 86 + 71 + 100 + 98 / 5
完成的第一个操作是 98/5。计算机计算出:
而不是所期望的:
使用括号可以解决这个问题:
average = (90 + 86 + 71 + 100 + 98) / 5
触发函数
三角函数用于计算等式中的正弦和余弦。默认情况下,Python 不知道如何计算正弦和余弦,但是一旦导入了适当的库,它就可以了。单位为弧度。
# Import the math library
# This line is done only once, and at the very top
# of the program.
from math import *
# Calculate x using sine and cosine
x = sin(0) + cos(0)
自定义公式计算器
一个程序可以用 Python 计算一辆汽车用 10.5 加仑汽油行驶 294 英里的里程。
m = 294 / 10.5
print(m)
这个程序可以通过使用变量来改进。这允许在不修改等式的情况下在代码中容易地改变值。
m = 294
g = 10.5
m2 = m / g # This uses variables instead
print(m2)
好的变量名很重要。
这个节目本身其实很难理解。没有上下文,变量m和g没有什么意义。通过使用适当命名的变量,可以使程序更容易理解:
miles_driven = 294
gallons_used = 10.5
mpg = miles_driven / gallons_used
print(mpg)
现在,即使一个非程序员也可能看着这个程序并对它的功能有一个很好的想法。另一个好的和不好的变量命名的例子:
# Hard to understand
ir = 0.12
b = 12123.34
i = ir * b
# Easy to understand
interest_rate = 0.12
account_balance = 12123.34
interest_amount = interest_rate * account_balance
在空闲编辑器中,可以编辑先前的行,而无需重新键入。将光标移动到该行并按回车键即可。它将被复制到当前行。
在>>>提示符下输入 Python 代码很慢,一次只能输入一行。也不可能保存代码以便其他人可以运行它。谢天谢地,有一种更好的方法来输入 Python 代码。
可以使用脚本输入 Python 代码。脚本是一系列将被一次执行的 Python 代码行。要创建脚本,打开一个新窗口,如下图所示。
输入脚本
您可能希望使用不同的程序来创建您的脚本,如 Wing IDE 或 PyCharm。这些程序比 Python 自带的空闲程序更容易、更强大。
进入计算汽油里程的 Python 程序,然后保存文件。将文件保存到闪存驱动器、网络驱动器或您选择的其他位置。Python 程序应该总是以.py结尾。见下图。
保存脚本
点击运行菜单,选择运行模块,运行输入的程序。尝试将程序更新为行驶里程和使用加仑数的不同值。
小心,常见错误!
从这一点开始,几乎所有输入的代码都应该在脚本/模块中。不要在 IDLE >>>提示符下输入你的程序。在此键入的代码不会被保存。如果发生这种情况,就需要重新开始。这是新程序员非常容易犯的错误。
如果这个程序能够与用户交互并询问用户行驶的英里数和使用的加仑数,那么它将会更加有用。这可以通过input语句来完成。参见下面的代码:
# This code almost works
miles_driven = input("Enter miles driven:")
gallons_used = input("Enter gallons used:")
mpg = miles_driven / gallons_used
print("Miles per gallon:", mpg)
运行这个程序会向用户询问英里和加仑,但它会产生一个奇怪的错误,如下图所示。
运行 MPG 程序时出错
这个错误的原因可以通过稍微修改程序来说明:
miles_driven = input("Enter miles driven:")
gallons_used = input("Enter gallons used:")
x = miles_driven + gallons_used
print("Sum of m + g:", x)
运行上面的程序会产生如下所示的输出。
添加不正确
这个程序不会把这两个数字加在一起:它只是把一个数字放在另一个数字之后。这是因为程序不知道用户将输入数字。用户可以输入 Bob 和 Mary,将这两个变量加在一起就是 BobMary,这样更有意义。
为了告诉计算机这些是数字,有必要用一个int( )或一个float( )包围input函数。前者用于整数,后者用于浮点数。
最终工作程序:
# Sample Python/Pygame Programs
# Simpson College Computer Science
#http://programarcadegames.com/
#http://simpson.edu/computer-science/
# Explanation video:http://youtu.be/JK5ht5_m6Mk
# Calculate Miles Per Gallon
print("This program calculates mpg.")
# Get miles driven from the user
miles_driven = input("Enter miles driven:")
# Convert text entered to a
# floating point number
miles_driven = float(miles_driven)
# Get gallons used from the user
gallons_used = input("Enter gallons used:")
# Convert text entered to a
# floating point number
gallons_used = float(gallons_used)
# Calculate and print the answer
mpg = miles_driven / gallons_used
print("Miles per gallon:", mpg)
另一个例子,计算物体的动能:
# Sample Python/Pygame Programs
# Simpson College Computer Science
#http://programarcadegames.com/
#http://simpson.edu/computer-science/
# Calculate Kinetic Energy
print("This program calculates the kinetic energy of a moving object.")
m_string = input("Enter the object’s mass in kilograms: ")
m = float(m_string)
v_string = input("Enter the object’s speed in meters per second: ")
v = float(v_string)
e = 0.5 * m * v * v
print("The object has " + str(e) + " joules of energy.")
为了缩短程序,可以将input语句嵌套到float语句中。例如,这几行代码:
milesDriven = input("Enter miles driven:")
milesDriven = float(milesDriven)
执行与此行相同的操作:
milesDriven = float(input("Enter miles driven:"))
在这种情况下,input功能的输出被直接输入到float功能中。哪一个都行,选择哪个是程序员的喜好问题。然而,能够理解这两种形式是很重要的。
回顾
多项选择测验
What is the correct code to print out the words ’Hello World’ to the screen? print (Hello World) print ’Hello World’ print {’Hello World’} print Hello World print [’Hello World’] print ("Hello World") print {’Hello World’} What does this code output? a = 1 b = 3 print(a + b) A+B a+b "a+b" 4 1+3 Nothing, the code is invalid. What does this code output? a = 1 b = 3 print("a+b") A+B a+b "a+b" The values of a and b added together. 10 Nothing, the code is invalid. What does this code output? print("The answer to 10+10 is," 10+10) The answer to 10+10 is 10+10 The answer to 10+10 is 20 The answer to 10+10 is10+10 The answer to 10+10 is20 The answer to 10+10 is,10+10 The answer to 10+10 is,20 Nothing, the code is invalid. What does this code output? # print("Hello") Hello "Hello" Nothing, there is an error in the code. Nothing, the code is commented out. What does this code output? x = 10 print("x") "x" x 10 Nothing What does this code output? x = 10 x + 1 print(x) 10 11 "x" x Nothing What does this code output? x = 10 + 6 / 2 x = x + 1 print(x) 8 9 13 14 Nothing What does this code output? x = input("Enter a value:") print(x / 2) 10 0 The value the user entered. The value the user entered divided by two. An error because the value was not converted to a number. What does this code output? print("Have a "great" day!") "Have a "great" day!" Have a "great" day! Have a great day! Nothing, the double quotes make for a syntax error. What does this code output? print("Save in c:\new folder") Save in c:\new folder Save in c: ew folder Save in c:ew folder Nothing, the escape code makes for a syntax error.
简答工作表
Write a line of code that will print your name. How do you enter a comment in a program? What do the following lines of code output? ALSO: Why do they give a different answer? print(2 / 3) print(2 // 3) Write a line of code that creates a variable called pi and sets it to an appropriate value. Why does this code not work? A = 22 print(a) All of the variable names below can be used. But which ONE of these is the better variable name to use? a A Area AREA area area_of_rectangle Area_Of_Rectangle Which of these variables names are not allowed in Python? (More than one might be wrong. Also, this question is not asking about improper names, just names that aren’t allowed. Test them if you aren’t sure.) apple Apple APPLE Apple2 1Apple account number account_number account.number accountNumber account# pi PI fred Fred GreatBigVariable greatBigVariable great_big_variable great.big.variable 2x x2x total% #left Why does this code not work? print(a) a = 45 Explain the mistake in this code: pi = float(3.14) This program runs, but the code still could be better. Explain what is wrong with the code. radius = float(input("Radius:")) x = 3.14 pi = x area = pi * radius ** 2 print(area) Explain the mistake in the following code: x = 4 y = 5 a = ((x) * (y)) print(a) Explain the mistake in the following code: x = 4 y = 5 a = 3(x + y) print(a) Explain the mistake in the following code: radius = input(float("Enter the radius:")) Do all these print the same value? Which one is better to use and why? print(2/3+4) print(2 / 3 + 4) print( 2 / 3+ 4 ) What is a constant? How are variable names for constants different than other variable names? What is a single quote and what is a double quote? Give and label an example of both. Write a Python program that will use escape codes to print a double quote and a new line using the Window’s standard. (Note: I’m asking for the Window’s standard here. Look it up out of Chapter 1.) Can a Python program print text to the screen using single quotes instead of double quotes? Why does this code not calculate the average? print(3 + 4 + 5 / 3) What is an operator in Python? What does the following program print out? x = 3 x + 1 print(x) Correct the following code: user_name = input("Enter your name: )" Correct the following code: value = int(input(print("Enter your age")))
锻炼
查看附录中本章附带的练习。
三、什么是计算机语言?
什么造就了计算机语言?为什么电脑会有?为什么有这么多不同的计算机语言?
做基本编程不需要理解这些问题的答案,就像开车不需要理解引擎如何工作一样。然而,要进步到一个更高的水平,它是。本章提供了一个简短的解释来帮助您开始。
编程简史
计算机是电子的,而且是数字化的。对计算机来说,一切都是用导线上没有电压或有电压来表示的。没有电压对电脑来说就是零,有电压就是一。如果没有多个 1 和 0 的组合,计算机实际上无法计算出比这更高的数。
在早期,开关被用来将 1 或 0 载入计算机内存。下图,由维基共享资源 ( http://en.wikipedia.org/wiki/File:Altair_Computer_Front_Panel.jpg )提供,展示了一台牛郎星 8800。前面板开关用于加载程序。灯光显示了产量。没有监视器。
牛郎星 8800
每组开关代表一个数字。每一个数字都代表计算机要执行的数据或指令。这种只用 1 和 0 来表示数字的系统叫做二进制数字系统。这种类型的计算机语言被称为 1GL(第一代语言)。注意:没有一种语言叫做 1GL,它只是第一代语言的缩写。1GL 与机器的本地语言(机器语言)是一回事,其中数字代表程序的命令和数据。
二进制数通常以四个一组来表示。例如:
1010 0010 0011
数据和计算机指令都是以二进制存储的。机器语言是代表计算机解释的指令的二进制数。然而,并不是所有的二进制数据都是机器语言。文档、数据库和财务数字等数据也以二进制形式存储在计算机中。当然,这些数据不是由计算机运行的。
对通过开关输入程序的一个改进是十六进制代码的使用。大多数人使用的十进制数字是数字 0-9。十六进制使用数字 0–9 和 A–F 来表示一组四个交换机,或数字 0–15。请参见下表,了解二进制、十进制和十六进制之间的关系。
| 二进制的 | 小数 | 十六进制的 | | --- | --- | --- | | Zero | Zero | Zero | | one | one | one | | Ten | Two | Two | | Eleven | three | three | | One hundred | four | four | | One hundred and one | five | five | | One hundred and ten | six | six | | One hundred and eleven | seven | seven | | One thousand | eight | eight | | One thousand and one | nine | nine | | One thousand and ten | Ten | A | | One thousand and eleven | Eleven | B | | One thousand one hundred | Twelve | C | | One thousand one hundred and one | Thirteen | D | | One thousand one hundred and ten | Fourteen | E | | One thousand one hundred and eleven | Fifteen | F | | 1 0000 | Sixteen | Ten | | 1 0001 | Seventeen | Eleven |为了使输入程序更容易,后来的计算机允许用户用汇编语言输入程序。每个命令都使用一个助记符,一个叫做编译器的程序会把助记符转换成代表命令的数字。汇编语言也被称为 2GL 语言,或第二代语言。
下图显示了一个示例汇编语言程序的一部分,也是由维基共享资源 ( http://en.wikipedia.org/wiki/File:Altair_Computer_Front_Panel.jpg )提供的。
示例汇编语言
虽然这是一个进步,但它仍然不太容易编程。下一代语言允许更高层次的抽象。第一批第三代语言(COBOL、FORTRAN 和 LISP)更容易理解和编程。
第二代和第三代语言使用一种叫做编译器的程序。编译器把用户输入的程序(称为源代码)转换成机器代码。然后程序员运行机器代码。原始源代码没有运行。
如果一个程序中有几段源代码,可以用一个叫做链接器的程序把它们链接成一个程序。链接器在编译器生成的机器码上运行,生成最终程序。这个最终的程序就是用户运行的,不需要原始的源代码。
编译器和连接器
编译成机器语言的一个缺点是程序只适用于特定类型的机器。为 Windows 电脑编译的程序不能在苹果 Macintosh 电脑或 Linux 电脑上运行。
因为整个编译和链接步骤对新程序员来说可能很复杂,所以一些语言使用解释器来运行。这些程序查看源代码,并即时将其解释为机器语言指令。它还允许相同的程序在 Windows、Mac 和 Unix 计算机上运行,前提是每个平台都有可用的解释程序。
使用解释器的缺点是通过解释器操作比用机器的母语操作要慢。
解释者
Python 是解释型语言的一个例子。用 Python 开发比 C 容易,但 Python 运行速度较慢,必须有 Python 解释器才能工作。
像 Java 这样的语言使用一个系统,在这个系统中,程序被编译成运行在 Java 虚拟机(JVM)上的机器代码,而不是实际的机器。另一种流行的语言是 C#,这是一种运行在虚拟执行系统(VES)虚拟机上的公共语言基础设施(CLI)语言。对这些的全面讨论超出了本书的范围,但是请随意阅读。
今天有许多不同的计算机语言。因为计算机执行如此多类型的任务,所以已经开发了专门用于这些任务的不同语言。像 C 这样的语言适合于操作系统和小型嵌入式计算机。像 PHP 这样的其他语言专门用于创建网页。Python 是一种通用语言,其特点是易于使用。
Tiobe 公司在其每月更新的索引中记录了各种编程语言的流行程度。这是一个好主意,看看这里,以及像骰子 ( http://www.dice.com/ ))这样的就业安置板,以了解什么语言是流行的。
令人欣慰的是,几乎所有的语言都有相同的共同点,一旦一种语言被学会,同样的理论将适用于其他语言。
对于有趣的计算历史,我推荐看罗伯特·X·克林格利的《书呆子的胜利》,这是一个关于计算起源的三集系列。这些电影非常有趣,你的整个家庭都会喜欢。如果你对阅读比对视频更感兴趣,我也推荐《偶然的帝国》这本书。
那些视频之后会发生什么?他们甚至没有报道互联网的诞生!要了解更多,请查看罗伯特·克瑞格利的视频系列《书呆子 2.0.1》。
回顾
多项选择测验
Which of these is the best example of a binary number 101101 82 3FA GAF Which of these is the best example of a decimal number? 101101 82 3FA GAF Which of these is the best example of a hexadecimal number? 101101 82 3FA GAF What is the decimal number equivalent to the binary number “100”? 1 2 3 4 8 None of the above What is source code? Runs source code directly, without compiling The machine code the computer runs Converts source code to machine code The program the developer types into the computer Links machine code together into one big program What is machine code? Runs source code directly, without compiling Converts source code to machine code The native code the computer runs The program the developer types into the computer Links machine code together into one big program What is a compiler? The machine code the computer runs Converts source code to machine code The program the developer types into the computer Links machine code together into one big program Runs source code directly, without compiling What is an interpreter? Converts source code to machine code Runs source code directly, without compiling The program the developer types into the computer The machine code the computer runs Links machine code together into one big program What is a linker? Links machine code together into one big program Converts source code to machine code The program the developer types into the computer The machine code the computer runs Runs source code directly, without compiling What is a first generation language (1GL)? Assembly language Language like Python or C that has logical structures Machine language A language built for a specific purpose What is a second generation language (2GL)? Language like Python or C that has logical structures Assembly language Machine language A language built for a specific purpose What is a third generation language (3GL)? A language built for a specific purpose Assembly language Machine language Language like Python or C that has logical structures
简答工作表
Give an example of a binary number. (While a number such as 1 can be a binary, decimal, and hexadecimal number, try coming up with an example that better illustrates the differences between the different bases of numbers.) Give an example of a decimal number. Give an example of a hexadecimal number. Convert the numbers 1, 10, 100, 1000, and 10000 from binary to decimal. What is a compiler? What is source code? What is machine language? (Don’t just say binary. That’s not correct.) What is a first generation language? (Don’t just say binary. That’s not correct.) What is a second generation language? What is a third generation language? (Explain, don’t just give one example.) What is an interpreter and how does it differ from a compiler? Search the Web and find some of the most popular programming languages. List the web site(s) you got the information from and what the languages are. Look at the job boards and see what languages people are looking for. List the languages and the job board you looked at. What is the difference between the syntax and semantics of a language? Pick a piece of technology, other than a computer you use regularly. Briefly describe the hardware and software that run on it.
锻炼
查看附录中本章附带的练习。
四、问答游戏和if语句
我们如何判断一个玩家是否已经击败了高分?我们怎么知道他的生命是否已经耗尽?我们怎么知道她是否有打开锁着的门所需的钥匙?
我们需要的是if语句。if语句也称为条件语句。(当你想给每个人留下你有多聪明的印象时,你可以使用条件语句这个术语。)的if语句允许计算机做出决定。外面热吗?飞船已经到屏幕边缘了吗?从账户中取出的钱太多了吗?程序可以用if语句测试这些条件。
基本比较
这里有几个if语句的例子。第一部分设置了在if语句中使用的两个变量(a和b)。然后两个if语句展示了如何比较变量,看是否一个大于另一个。
# Variables used in the example if statements
a = 4
b = 5
# Basic comparisons
if a < b:
print("a is less than b")
if a > b:
print("a is greater than b")
print("Done")
因为 a 小于 b,所以如果运行这段代码,第一条语句将会打印出来。如果变量 a 和 b 都等于 4,那么上面的两个if语句都不会打印出任何东西。数字 4 不大于 4,所以if语句会失败。
为了显示程序的流程,可以使用流程图。即使没有编程入门,大多数人也能理解流程图。看看你对下图的理解程度。
流程图
这本书跳过了对流程图的深入研究,因为它很无聊。但是如果你想成为一名超级巨星程序员,请在 http://en.wikipedia.org/wiki/Flowchart 阅读更多信息。
前面的示例检查了大于或小于。相等的数字不会通过测试。要检查大于或等于a的值,以下示例显示了如何执行此操作:
if a <= b:
print("a is less than or equal to b")
if a >= b:
print("a is greater than or equal to b")
<=和>=符号必须按顺序使用,不能有空格。比如=<不行,< =也不行。
在写出这些语句时,有些人喜欢使用≤符号。例如:
if a ≤ b:
这个≤符号实际上在程序中不起作用。再加上大多数人不知道如何在键盘上轻松打字。(以防你好奇,要键入它,按住“alt”键,同时在数字键盘上键入 243。)所以在写出代码的时候,要记住是<=而不是≤。
下一组代码检查两项是否相等。等于的运算符是==,不等于的运算符是!=。这是他们的行动。
# Equal
if a == b:
print("a is equal to b")
# Not equal
if a != b:
print("a and b are not equal")
学习何时使用=和==。
使用==和=的时候很容易混淆。如果你想知道它们是否相等,请使用==,如果你想赋值,请使用=。
混合使用=和==运算符时最常见的两个错误如下所示:
# This is wrong
a == 1
# This is also wrong
if a = 1:
print("A is one")
停下来!请花点时间回头仔细研究最后两个代码示例。通过确保您了解何时使用=和==来节省时间。不要猜测。
刻痕
缩进很重要。只有当语句为真时,缩进的if语句下的每一行才会被执行:
if a == 1:
print("If a is one, this will print.")
print("So will this.")
print("And this.")
print("This will always print because it is not indented.")
缩进必须相同。这个代码不起作用。
if a == 1:
print("Indented two spaces.")
print("Indented four. This will generate an error.")
print("The computer will want you to make up your mind.")
一旦一个if语句结束,就不可能重新缩进再返回。必须再次进行测试。
if a == 1:
print("If a is one, this will print.")
print("So will this.")
print("This will always print because it is not indented.")
print("This will generate an error. Why it is indented?")
使用和/或
一个if语句可以通过用and和or链接比较来检查多个条件。这些也被认为是运算符,就像+或- are 一样。
# And
if a < b and a < c:
print("a is less than b and c")
# Non-exclusive or
if a < b or a < c:
print("a is less than either b or c (or both)")
请重复一遍。
一个常见的错误是在根据多个条件检查变量时忽略变量。下面的代码不起作用,因为计算机不知道对照变量c检查什么。它不会假设对照a进行检查。
# This is not correct
if a < b or < c:
print("a is less than b and c")
布尔变量
Python 支持布尔变量。什么是布尔变量?布尔变量可以存储一个True或一个值False。布尔代数是由乔治·布尔早在 1854 年开发的。要是他知道他的工作作为现代计算机逻辑的基础会变得多么重要就好了!
一个if语句需要一个表达式来计算True或False。看起来奇怪的是,如果一个变量已经计算为True或False,它实际上不需要做任何比较。
# Boolean data type. This is legal!
a = True
if a:
print("a is true")
我上学的时候,流行说一些虚假的话。等三秒钟,然后喊“不!”嗯,连你的电脑都认为这很无聊。如果您打算这样做,您必须从not操作符开始。下面的代码使用not在真和假之间翻转a的值。
# How to use the not function
if not(a):
print("a is false")
因为not是一个操作符而不是一个函数,圆括号是不必要的。这也是合法的:
# How to use the not function
if not a:
print("a is false")
也可以使用带有and和or操作符的布尔变量。
a = True
b = False
if a and b:
print("a and b are both true")
谁知道真/假可能很难?
也可以将一个变量赋给比较结果。在下面的代码中,比较了变量a和b。如果相等,c就是True;否则c将会是False。
a = 3
b = 3
# This next line is strange-looking, but legal.
# c will be true or false, depending if
# a and b are equal.
c = a == b
# Prints value of c, in this case True
print(c)
零表示错误。其他都是真的。
可以创建一个条件不为真或假的if语句。这通常是不希望的,但是理解计算机在搜索问题时如何处理这些值是很重要的。下面的语句是合法的,将导致文本被打印出来,因为if语句中的值是非零的:
if 1:
print("1")
if "A":
print("A")
下面的代码不会打印出任何内容,因为 if 语句中的值为零,被视为 False。非零值被认为是真的。
if 0:
print("Zero")
在下面的代码中,第一个if语句似乎可以工作。问题是,即使变量a不等于b,它也总是触发为真。这是因为b本身被认为是真的。
a = "c"
if a == "B" or "b":
print("a is equal to b. Maybe.")
# This is a better way to do the if statement.
if a == "B" or a == "b":
print("a is equal to b.")
Else 和 Else If
下面的代码将从用户那里获取温度,如果温度高就打印出来。
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
print("It is hot outside")
print("Done")
如果程序员希望代码在不热的情况下执行,她可以使用else语句。注意在if语句中else是如何与i对齐的,以及它是如何跟随着一个冒号的,就像if语句一样。
在if...else语句的情况下,一个代码块将总是被执行。如果语句评估为True,将执行第一个块;如果评估为False,将执行第二个块。
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
print("It is hot outside")
else:
print("It is not hot outside")
print("Done")
可以使用else...if语句将几个if语句链接在一起。Python 将其缩写为elif。
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
print("It is hot outside")
elif temperature < 30:
print("It is cold outside")
else:
print("It is not hot outside")
print("Done")
在下面的代码中,即使用户键入 120 度,程序也会输出“外面很热”。为什么呢?代码如何修复?
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
print("It is hot outside")
elif temperature > 110:
print("Oh man, you could fry eggs on the pavement!")
elif temperature < 30:
print("It is cold outside")
else:
print("It is ok outside")
print("Done")
文本比较
可以使用if语句来检查文本。
user_name = input("What is your name? ")
if user_name == "Paul":
print("You have a nice name.")
else:
print("Your name is ok.")
只有当用户输入“Paul”时,前面的例子才会匹配。如果用户输入“保罗”或“保罗”,它将不起作用。
一个常见的错误是忘记了被比较字符串的引号。在下面的例子中,计算机会认为Paul是一个存储值的变量。它将标记一个错误,因为它不知道变量Paul中存储了什么。
user_name = input("What is your name? ")
if user_name == Paul: # This does not work because quotes are missing
print("You have a nice name.")
else:
print("Your name is ok.")
多种文本可能性
当将一个变量与多个可能的文本字符串进行比较时,记住比较必须包括该变量是很重要的。例如:
# This does not work! It will always be true
if user_name == "Paul" or "Mary":
相反,代码应该是:
# This does work
if user_name == "Paul" or user_name == "Mary":
这是因为任何非零值,计算机都认为是指True。所以对计算机来说"Mary"和True是一回事,所以它会运行if语句中的代码。
不区分大小写的比较
如果程序需要匹配输入文本的大小写,最简单的方法就是将所有内容都转换成小写。这可以通过lower命令来完成。
学会麻木不仁。
下面的例子将获取用户输入的任何内容,将其转换为小写,然后进行比较。重要提示:不要将其与大写的字符串进行比较。如果用户输入被转换成小写字母,然后与大写字母进行比较,就不可能出现匹配。
user_name = input("What is your name? ")
if user_name.lower() == "paul":
print("You have a nice name.")
else:
print("Your name is ok.")
if 语句示例
下面的下一组示例代码贯穿了前面讨论的所有概念。
# Sample Python/Pygame Programs
# Simpson College Computer Science
#http://programarcadegames.com/
#http://simpson.edu/computer-science/
# Explanation video:http://youtu.be/pDpNSck2aXQ
# Variables used in the example if statements
a = 4
b = 5
c = 6
# Basic comparisons
if a < b:
print("a is less than b")
if a > b:
print("a is greater than than b")
if a <= b:
print("a is less than or equal to b")
if a >= b:
print("a is greater than or equal to b")
# NOTE: It is very easy to mix when to use == and =.
# Use == if you are asking if they are equal, use =
# if you are assigning a value.
if a == b:
print("a is equal to b")
# Not equal
if a != b:
print("a and b are not equal")
# And
if a < b and a < c:
print("a is less than b and c")
# Non-exclusive or
if a < b or a < c:
print("a is less than either a or b (or both)")
# Boolean data type. This is legal!
a = True
if a:
print("a is true")
if not a:
print("a is false")
a = True
b = False
if a and b:
print("a and b are both true")
a = 3
b = 3
c = a == b
print(c)
# These are also legal and will trigger as being true because
# the values are not zero:
if 1:
print("1")
if "A":
print("A")
# This will not trigger as true because it is zero.
if 0:
print("Zero")
# Comparing variables to multiple values.
# The first if statement appears to work, but it will always
# trigger as true even if the variable a is not equal to b.
# This is because "b" by itself is considered true.
a = "c"
if a == "B" or "b":
print("a is equal to b. Maybe.")
# This is the proper way to do the if statement.
if a == "B" or a == "b":
print("a is equal to b.")
# Example 1: If statement
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
print("It is hot outside")
print("Done")
# Example 2: Else statement
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
print("It is hot outside")
else:
print("It is not hot outside")
print("Done")
# Example 3: Else if statement
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
print("It is hot outside")
elif temperature < 30:
print("It is cold outside")
else:
print("It is not hot outside")
print("Done")
# Example 4: Ordering of statements
# Something with this is wrong. What?
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
print("It is hot outside")
elif temperature > 110:
print("Oh man, you could fry eggs on the pavement!")
elif temperature < 30:
print("It is cold outside")
else:
print("It is ok outside")
print("Done")
# Comparisons using string/text
# Note, this example does not work when running under Eclipse
# because the input will contain an extra carriage return at the
# end. It works fine under IDLE.
userName = input("What is your name? ")
if userName == "Paul":
print("You have a nice name.")
else:
print("Your name is ok.")
回顾
多项选择测验
Which statement will check if a is less than b? if a less than b: if a < b if a > b if a < b: if (a < b) if a >= b if a <= b: Which statement will check if a is equal to b? if a equals b: if a = b if a = b: if a == b: if a == b if a === b if a === b: Which statement will check if a is less than or equal to b? if a < or = b: if a <= b: if a < = b: if a >= b: if a =< b: if a < b or == b: if a <== b: Which statement will check if a is less b and less than c? if a < b and < c: if a < b & c: if a < b and a < c: if a < b and c: What will this code print? if 3 < 4: print("A") else: print("B") print("C") A A B B B C A C A B C Nothing, the code won’t run. What will this code print? if 3 < 4: print("A") else: print("B") print("C") A A B B B C A C A B C Nothing, the code won’t run. What will this code print? a = True if a: print("A") else: print("B") print("C") A A B B B C A C A B C Nothing, the code won’t run. What will this code print? a = True if not(a): print("A") else: print("B") print("C") A A B B B C A C A B C Nothing, the code won’t run. What will this code print? if 4 < 4: print("A") elif 3 < 4: print("B") else: print("C") print("D") A A B B B D A D A C Nothing, the code won’t run.
简答工作表
What is missing from this code? temperature = float(input("Temperature: ") if temperature > 90: print("It is hot outside.") else: print("It is not hot out.") Write a Python program that will take in a number from the user and print if it is positive, negative, or zero. Use a proper if/elif/else chain; don’t just use three if statements. Write a Python program that will take in a number from a user and print out Success if it is greater than -10 and less than 10, inclusive. This runs, but there is something wrong. What is it? user_input = input("A cherry is a: ") print("A. Dessert topping") print("B. Desert topping") if user_input.upper() == "A": print("Correct!") else: print("Incorrect.") There are two things wrong with this code that tests if x is set to a positive value. One prevents it from running, and the other is subtle. Make sure the if statement works no matter what x is set to. Identify both issues. x == 4 if x >= 0: print("x is positive.") else: print("x is not positive.") What three things are wrong with the following code? x = input("Enter a number: ") if x = 3 print("You entered 3") There are four things wrong with this code. Identify all four issues. answer = input("What is the name of Dr. Bunsen Honeydew’s assistant? ") if a = "Beaker": print("Correct!") else print("Incorrect! It is Beaker.") This program doesn’t work correctly. What is wrong? x = input("How are you today?") if x == "Happy" or "Glad": print("That is good to hear!") Look at the code below. Write you best guess here on what it will print. Next, run the code and see if you are correct. Clearly label your guess and the actual answer. Also, if this or any other example results in an error, make sure to state that an error occurred. While you don’t need to write an explanation, make sure you understand why the computer prints what it does. Don’t get caught flat-footed when you need to know later. x = 5 y = x == 6 z = x == 5 print("x=", x) print("y=", y) print("z=", z) if y: print("Fizz") if z: print("Buzz") Look at the code below. Write you best guess on what it will print. Next, run the code and see if you are correct. x = 5 y = 10 z = 10 print(x < y) print(y < z) print(x == 5) print(not x == 5) print(x != 5) print(not x != 5) print(x == "5") print(5 == x + 0.00000000001) print(x == 5 and y == 10) print(x == 5 and y == 5) print(x == 5 or y == 5) Look at the code below. Write you best guess on what it will print. Next, run the code and see if you are correct. print("3" == "3") print(" 3" == "3") print(3 < 4) print(3 < 10) print("3" < "4") print("3" < "10") print( (2 == 2) == "True" ) print( (2 == 2) == True ) print(3 < "3") What things are wrong with this section of code? The programmer wants to set the money variable according to the initial occupation the user selects. print("Welcome to Oregon Trail!") print("A. Banker") print("B. Carpenter") print("C. Farmer") user_input = input("What is your occupation?") if user_input = A: money = 100 else if user_input = B: money = 70 else if user_input = C: money = 50
锻炼
在附录中找到练习 3“创建一个测验”。
五、带有随机数和循环的猜谜游戏
开始学习图形之前的最后一步是学习如何循环一段代码。大多数游戏循环。他们一遍又一遍地重复同样的代码。例如,下面的数字猜谜游戏针对用户的每次猜测进行循环:
Hi! I’m thinking of a random number between 1 and 100.
--- Attempt 1
Guess what number I am thinking of: 50
Too high.
--- Attempt 2
Guess what number I am thinking of: 25
Too high.
--- Attempt 3
Guess what number I am thinking of: 17
Too high.
--- Attempt 4
Guess what number I am thinking of: 9
Too low.
--- Attempt 5
Guess what number I am thinking of: 14
Too high.
--- Attempt 6
Guess what number I am thinking of: 12
Too high.
--- Attempt 7
Guess what number I am thinking of: 10
Too low.
Aw, you ran out of tries. The number was 11.
等等,这跟图形和视频游戏有什么关系?很多。游戏显示的每一帧都是一次循环。你可能对游戏显示的每秒帧数(FPS)很熟悉。FPS 代表计算机每秒更新屏幕的次数。速率越高,游戏越流畅。(虽然超过 60 的 FPS 比大多数屏幕更新的速度都快,所以没有必要超过这个速度。)下图显示了游戏 Eve Online 和一个显示计算机每秒能够显示多少帧的图表。
视频游戏中的 FPS
这些游戏中的循环就像下图中的流程图一样。尽管现代游戏很复杂,但这个循环的内部类似于我们在第二章所做的计算器程序。获取用户输入。执行计算。输出结果。在电子游戏中,我们试图每秒钟重复 60 次。
游戏循环
甚至可以在其他循环中存在循环。真正的“循环循环”看看下图中的“绘制所有内容”框。这组代码循环遍历并绘制游戏中的每个对象。该循环位于绘制游戏每一帧的更大循环的内部,如下图所示。
绘制所有循环
Python 中有两种主要类型的循环:for循环和while循环。如果你想重复一定的次数,使用for循环。如果你想重复直到发生什么事情(比如用户点击退出按钮),那么使用一个while循环。
例如,一个for循环可以用来打印所有的学生记录,因为计算机知道有多少学生。需要使用一个while循环来检查用户何时点击鼠标按钮,因为计算机不知道要等待多长时间。
对于循环
下面的for循环示例运行了五次print语句。它可以很容易地运行 100 或 1,000,000 次,只需将 5 改为所需的循环次数。请注意for循环与if语句的相似之处。两者都以冒号结尾,并且都使用缩进来指定语句影响哪些行。
for i in range(5):
print("I will not chew gum in class.")
I will not chew gum in class.
I will not chew gum in class.
I will not chew gum in class.
I will not chew gum in class.
I will not chew gum in class.
第 1 行的i是一个变量,记录程序循环了多少次。这是一个新变量,可以用任何合法的变量名命名。程序员经常使用i作为变量名,因为 I 是 increment 的缩写。这个变量有助于跟踪循环应该何时结束。
range函数控制循环中代码运行的次数。在这种情况下,五次。
下一个示例代码将打印五次“请”,以及“我可以去商场吗?”只有一次。“我能去商场吗?”未缩进,因此它不是for循环的一部分,并且在for循环完成之前不会打印。
for i in range(5):
print("Please,")
print("Can I go to the mall?")
Please,
Please,
Please,
Please,
Please,
Can I go to the mall?
下一个代码示例采用前面的示例并缩进第 3 行。这一更改将导致程序打印“请”和“我可以去商场吗?”五次。既然语句已经缩进了“我能去商场吗?”现在是for循环的一部分,将像单词“Please”一样重复五次。
for i in range(5):
print("Please,")
print("Can I go to the mall?")
Please,
Can I go to the mall?
Please,
Can I go to the mall?
Please,
Can I go to the mall?
Please,
Can I go to the mall?
Please,
Can I go to the mall?
下面的代码将打印数字 0 到 9。请注意,循环从 0 开始,不包括数字 10。人们很自然地认为range(10)应该包括 10,但是它刚好在 10 之下停止。
for i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
一个程序不需要命名变量i;它可以被命名为其他名称。例如,如果一个程序员正在处理一个文本文件,她可能会使用line_number。
如果一个程序员想从 1 到 10,而不是从 0 到 9,有几种方法可以做到。第一种方法是给range函数发送两个数字,而不是一个。第一个数字是起始值;第二个刚好超出结束值。
这确实需要一些练习来适应这个想法,即for循环将包括第一个数字,但不包括列出的第二个数字。下面的例子指定了(1,11)的范围,数字 1 到 10 被打印出来。包括起始数字 1,但不包括结束数字 11。
for i in range(1, 11):
print(i)
1
2
3
4
5
6
7
8
9
10
另一种打印数字 1 到 10 的方法是仍然使用range(10)并让变量i从 0 到 9。但是就在打印出变量之前,程序员给它加了一。这也适用于打印数字 1 到 10。两种方法都可以。
# Print the numbers 1 to 10.
for i in range(10):
print(i + 1)
用一以外的数字计数
如果程序需要按 2s 计数或使用其他增量,这很容易。就像以前一样有两种方法。最简单的方法是向 range 函数提供第三个数字,告诉它按 2s 计数。第二种方法是从 1 开始计数,但是将变量乘以 2。下面的代码示例显示了这两种方法。
# Two ways to print the even numbers 2 to 10
for i in range(2,12,2):
print(i)
for i in range(5):
print((i + 1) * 2)
2
4
6
8
10
2
4
6
8
10
也可以通过给距离函数一个负的步长来倒计数到零。在下面的例子中,从 10 开始,下降到 0,但不包括 0,并以-1 为增量。创建这些循环最困难的部分是不小心交换了开始和结束的数字。程序从较大的值开始,所以它先运行。正常的for循环从range函数中首先列出的最小值开始递增计数。
for i in range(10, 0, -1):
print(i)
10
9
8
7
6
5
4
3
2
1
如果程序需要迭代的数字没有形成一个简单的模式,就有可能从列表中取出数字。(对列表的全面讨论包含在第八章中。这只是你能做的预览。)
for i in [2,6,4,2,4,6,7,4]:
print(i)
这将打印:
2
6
4
2
4
6
7
4
嵌套循环
试着预测下面的代码会输出什么。然后输入代码,看是否正确。
# What does this print? Why?
for i in range(3):
print("a")
for j in range(3):
print("b")
下一个代码块与上面的代码块几乎相同。第二个for循环缩进了一个制表位,因此它现在嵌套在第一个for循环内。这极大地改变了代码的运行方式。试试看。
# What does this print? Why?
for i in range(3):
print("a")
for j in range(3):
print("b")
print("Done")
我不会告诉你代码是做什么的。去电脑前看看。
保持累计总数
处理循环的一个常见操作是保存运行总数。这种“累计”代码模式在本书中被大量使用。保持一个分数的运行总数,合计一个人的帐户交易,使用总数来找到平均值,等等。您可能希望将这个代码清单加入书签,因为我们会多次引用它。在下面的代码中,用户输入五个数字,代码对它们的值求和。
total = 0
for i in range(5):
new_number = int(input("Enter a number: " ))
total += new_number
print("The total is: ", total)
注意,第 1 行创建了变量total,并将其初始数量设置为零。很容易忘记需要创建变量并将其初始化为零。如果没有它,计算机会在碰到第 4 行时报错。它不知道如何将new_number加到total上,因为还没有给total赋值。
一个常见的错误是用i到total代替new_number。请记住,我们保存的是用户输入值的累计,而不是当前循环计数的累计。
说到当前循环计数,我们可以用循环计数值来解决一些数学运算。例如:
如果你不熟悉这种公式,这只是一种奇特的表述方式:
s = 1 + 2 + 3 + 4 + 5...98 + 99 + 100
下面的代码将从 1 到 100 的所有数字相加。它演示了一个常见的模式,其中运行总数保存在一个循环中。这也使用一个单独的变量sum来跟踪运行总数。
# What is the value of sum?
sum = 0
for i in range(1, 101):
sum = sum + i
print(sum)
这里有一个不同的变体。它从用户那里获取五个数字,并计算用户输入零的次数:
total = 0
for i in range(5):
new_number = int(input( "Enter a number: "))
if new_number == 0:
total += 1
print("You entered a total of", total, "zeros")
理解嵌套的for循环和运行总数的程序员应该能够预测下面代码的输出。
# What is the value of a?
a = 0
for i in range(10):
a = a + 1
print(a)
# What is the value of a?
a = 0
for i in range(10):
a = a + 1
for j in range(10):
a = a + 1
print(a)
# What is the value of a?
a = 0
for i in range(10):
a = a + 1
for j in range(10):
a = a + 1
print(a)
这一部分不要看得太快。试一试,预测上面代码的输出。然后复制到一个 Python 程序里运行一下,看看自己是不是对的。如果你不是,找出原因。
循环示例
这个示例代码涵盖了常见的for循环,并展示了它们是如何工作的。
# Sample Python/Pygame Programs
#http://programarcadegames.com/
# Print ’Hi’ 10 times
for i in range(10):
print("Hi")
# Print ’Hello’ 5 times and ’There’ once
for i in range(5):
print("Hello")
print("There")
# Print ’Hello’ ’There’ 5 times
for i in range(5):
print("Hello")
print("There")
# Print the numbers 0 to 9
for i in range(10):
print(i)
# Two ways to print the numbers 1 to 10
for i in range(1, 11):
print(i)
for i in range(10):
print(i + 1)
# Two ways``to
for i in range(2, 12, 2):
print(i)
for i in range(5):
print((i + 1) * 2)
# Count down from 10 down to 1 (not zero)
for i in range(10, 0, -1):
print(i)
# Print numbers out of a list
for i in [2, 6, 4, 2, 4, 6, 7, 4]:
print(i)
# What does this print? Why?
for i in range(3):
print("a")
for j in range(3):
print("b")
# What is the value of a?
a = 0
for i in range(10):
a = a + 1
print(a)
# What is the value of a?
a = 0
for i in range(10):
a = a + 1
for j in range(10):
a = a + 1
print(a)
# What is the value of a?
a = 0
for i in range(10):
a = a + 1
for j in range(10):
a = a + 1
print(a)
# What is the value of sum?
sum = 0
for i``in
sum = sum + i
while 循环
当一个程序知道它需要重复一段代码一定的次数时,就会使用一个for循环。当一个程序需要循环直到一个特定的条件发生时,使用一个while循环。
奇怪的是,while循环可以用在任何使用for循环的地方。它可用于循环,直到增量变量达到某个值。如果一个while循环可以做任何事情,为什么还要有一个for循环呢?for循环更容易使用和编码。一个看起来像这样的for循环:
for i in range(10):
print(i)
…可以通过如下所示的while循环来完成:
i = 0
while i < 10:
print(i)
i = i + 1
while循环的第 1 行设置了一个“sentinel”变量,用于计算循环执行的次数。这在一个for循环中自动发生,减少了一行代码。第 2 行包含实际的while循环。while循环的格式与if语句非常相似。如果条件成立,循环中的代码将重复。第 4 行增加了增量值。在一个for循环中,这自动发生,消除了另一行代码。从代码中可以看出,for循环比while循环更紧凑,也更容易阅读。否则,程序会用一个while循环做所有的事情。
一个常见的错误是混淆了for循环和while循环。下面的代码显示了一个无法在for循环和while循环之间做出决定的程序员。
while range(10):
print(i)
不要将range与while循环一起使用!
range功能仅适用于for循环。不要与while回路一起使用!
使用增量运算符
增量运算符通常与while循环一起使用。可以简化代码:
i = i + 1
包含以下内容:
i += 1
在while循环中,它看起来像是:
i = 0
while i < 10:
print(i)
i += 1
这也可以用减法和乘法来完成。例如:
i *= 2
与以下内容相同:
i = i * 2
看看你能不能想出这个会打印出什么:
i = 1
while i <= 2 ** 32:
print(i)
i *= 2
循环,直到用户想要退出
一个非常常见的操作是循环,直到用户执行退出请求:
quit = "n"
while quit == "n":
quit = input("Do you want to quit? ")
循环可能有几种退出方式。使用布尔变量来触发事件是一种处理方式。这里有一个例子:
done = False
while not done:
quit = input("Do you want to quit? ")
if quit == "y":
done = True
attack = input("Does your elf attack the dragon? ")
if attack == "y":
print("Bad choice, you died.")
done = True
尽管这并不完美,因为如果用户说她想退出,代码仍然会询问她是否想攻击龙。你怎么解决这个问题?
下面是一个使用while循环的例子,其中代码重复,直到值足够接近零:
value = 0
increment = 0.5
while value < 0.999:
value += increment
increment *= 0.5
print(value)
while 循环的常见问题
程序员想从 10 开始倒数。出了什么问题,如何解决?
i = 10
while i == 0:
print(i)
i -= 1
这个试图数到 10 的循环有什么问题?运行时会发生什么?应该怎么修?
i = 1
while i < 10:
print(i)
while 循环示例
这里有一个程序,涵盖了我们刚刚谈到的while循环的不同用法。
# Sample Python/Pygame Programs
#http://programarcadegames.com/
# A while loop can be used anywhere a for loop is used:
i = 0
while i < 10:
print(i)
i = i + 1
# This is the same as:
for i in range(10):
print(i)
# It is possible to short hand the code:
# i = i + 1
# With the following:
# i += 1
# This can be done with subtraction, and multiplication as well.
i = 0
while i < 10:
print(i)
i += 1
# What would this print?
i = 1
while i <= 2**32:
print(i)
i *= 2
# A very common operation is to loop until the user performs
# a request to quit
quit = "n"
while quit == "n":
quit = input("Do you want to quit? ")
# There may be several ways for a loop to quit. Using a boolean
# to trigger the event is a way of handling that.
done = False
while not done:
quit = input("Do you want to quit? ")
if quit == "y":
done = True
attack =``input
if attack == "y":
print("Bad choice, you died.")
done = True
value = 0
increment = 0.5
while value < 0.999:
value += increment
increment *= 0.5
print(value)
# -- Common problems with while loops --
# The programmer wants to count down from 10
# What is wrong and how to fix it?
i = 10
while i == 0:
print(i)
i -= 1
# What is wrong with this loop that tries
# to count to 10? What will happen when it is run?
i = 1
while i < 10:
print(i)
随机数
随机数在计算机科学中大量用于涉及游戏或模拟的程序。
randrange 函数
默认情况下,Python 不知道如何生成随机数。有必要让 Python 导入一个可以创建随机数的代码库。所以要使用随机数,首先应该出现在程序顶部的是一个import语句:
import random
就像 pygame 一样,重要的是不要创建与导入的文件同名的文件。创建一个名为random.py的文件将导致 Python 开始导入那个文件,而不是创建随机数的系统库。
之后,可以用randrange函数创建随机数。例如,这段代码创建从 0 到 49 的随机数。默认情况下,下限为 0。
my_number = random.randrange(50)
下一个代码示例生成 100 到 200 之间的随机数。就像range函数一样,第二个参数指定了一个不包含的上限。因此,如果您想要 200 以内的随机数,请指定 201。
my_number = random.randrange(100, 201)
如果你不想要一个数字,而是一个随机的项目呢?这需要一份清单。在第八章之前,我们不会详细介绍列表,但是为了给你一个从列表中随机选择一个项目的预览,请看下面:
my_list = ["rock", "paper", "scissors"]
random_index = random.randrange(3)
print(my_list[random_index])
random功能
所有先前的代码都生成整数。如果需要浮点数,程序员可以使用random功能。
下面的代码生成一个从 0 到 1 的随机数,例如 0.4355991106620656。
my_number = random.random()
通过一些简单的数学运算,这个数字是可以调整的。例如,下面的代码生成一个介于 10 和 15 之间的随机浮点数:
my_number = random.random() * 5 + 10
回顾
多项选择测验
What does this code print? for x in range(4): print("Hello") The word Hello 3 times The word Hello 4 times The word Hello 5 times It will print nothing It will print Hello forever Nothing, it won’t run What does this code print? for y in range(4): print("y") The numbers 0 to 3 The numbers 0 to 4 The numbers 1 to 3 The numbers 1 to 4 It will print “y” four times Nothing, it won’t run What does this code print? for y in range(4): print(y) The numbers 0 to 3 The numbers 0 to 4 The numbers 1 to 3 The numbers 1 to 4 It will print “y” four times Nothing, it won’t run What does this code print? for y in range(1, 11): print(y) The numbers 0 to 11 The numbers 1 to 11 The numbers 1 to 10 The numbers 0 to 10 Nothing, it won’t run What does this code print? for y in range(2, 12, 2): print(y + 1) The even numbers 2 to 12 The even numbers 2 to 10 The odd numbers 3 to 11 The odd numbers 3 to 13 Nothing, it won’t run What does this code print? a=0 for i in range(10): a += 1 print(a) 9 10 11 Nothing, it won’t run What does this code print? a = 0 for i in range(10): a += 1 for j in range(10): a += 1 print(a) 10 20 18 100 Nothing, it won’t run What does this code print? a = 0 for i in range(10): for j in range(10): a += 1 print(a) 10 20 110 100 Nothing, it won’t run What does this code print? a = 0 for i in range(10): a += 1 for j in range(10): a += 1 print(a) 10 20 110 100 Nothing, it won’t run When should a programmer use a for loop instead of a while loop? for loops are used to when there is a set number of loops for loops are used to loop until a condition is true while loops should always be used for loops should always be used What does this do? x = random.randrange(50) The number 50 A random integer 0 to 49 (inclusive) A random integer 1 to 50 (inclusive) A random integer 1 to 49 (inclusive) A random integer 0 to 50 (inclusive) A random integer 1 to 51 (inclusive) What does this do? x = random.randrange(1, 50) A random integer 0 to 49 (inclusive) A random integer 1 to 50 (inclusive) A random integer 1 to 49 (inclusive) A random integer 0 to 50 (inclusive) A random integer 1 to 51 (inclusive)
- 数字 50
What does this do? x = random.random() * 10 A random floating-point number from 0 to 10 A random integer from 0 to 10 A random integer from 0 to 9 A random integer from 0 to 1
简答工作表
注意:不要创建只循环一次的循环。这说不通。默认情况下,Python 会运行一次代码。避免这样的循环:
for i in range(1):
# Do something.
Write a Python program that will use a for loop to print your name 10 times, and then the word “Done” at the end. Write a Python program that will use a for loop to print “Red” and then “Gold” 20 times. (Red Gold Red Gold Red Gold… all on separate lines. Don’t use \n.) Write a Python program that will use a for loop to print the even numbers from 2 to 100, inclusive. Write a Python program that will use a while loop to count from 10 down to, and including, 0. Then print the words “Blast off!” Remember, use a WHILE loop, don’t use a FOR loop. There are three things wrong with this program. List each. print("This program takes three numbers and returns the sum.") total = 0 for i in range(3): x = input("Enter a number: ") total = total + i print("The total is:", x) Write a program that prints a random integer from 1 to 10 (inclusive). Write a program that prints a random floating-point number somewhere between 1 and 10 (inclusive). Do not make the mistake of generating a random number from 0 to 10 instead of 1 to 10. Write a Python program that will:
- 向用户询问七个数字
- 打印这些数字的总和
- 打印正条目的计数、等于零的条目数以及负条目数。使用一个
if、elif、else链,而不仅仅是三个if语句。
Coin flip tosser:
- 创建一个打印随机 0 或 1 的程序。
- 打印头部或尾部,而不是 0 或 1。使用
if语句来实现。不要从列表中选择,如章节所示。 - 添加一个循环,使程序这样做 50 次。
- 创建翻转的正面数量和反面数量的累计。
Write a program that plays rock, paper, scissors:
- 创建一个随机打印 0、1 或 2 的程序。
- 扩展程序,使其使用
if语句随机打印石头、布或剪刀。不要从列表中选择,如章节所示。 - 添加到程序中,这样它首先询问用户他们的选择。
- (如果让他们输入 1、2 或 3,会更容易些。)
- 添加一个条件语句来判断谁赢了。
锻炼
查看附录中本章附带的“骆驼”练习。