(首页)开始编程之旅 翻译自Lee Harr的Start Programming

本文是使用pygsear+pygame作为开发环境,以初级用户角度来分步分阶段学习PYTHON基本概念,并以小游戏开发项目为具体案例,介绍的十分详细。编写风格清新朴实,没有象一般教科书那样枯燥,极其适合初级用户来激发兴趣时使用。

1. StartProgramming-1-4 控制Control

Now that you can make comparisons, you can control the flow of your programs.

现在你可以做比较了,你也可以控制程序的流向。

Start up the interact.py program again, and try this:

再次运行程序 interact.py 并尝试下面的语句:

   1 choice = 'blast'
   2 if choice == 'blast':
   3     pete.blast()

The drawing on the right is a flow chart and it represents the code on the left. You can follow the flow by starting at the top, following the lines, and acting on the instructions in the boxes.

右边的图样是一个流程图代表了左边的代码。你可以从最上面跟随流程,在线上流动,并且执行在方框中的指令。

In the code, notice how the line after the if statement is indented.

在代码中,注意 if 后面的语句是怎样缩进的。

Indentation is how Python knows those statements are all run only if the condition is True. Like this:

缩进使得 Python 知道当 if 的结果是 True 时,哪些语句可以被运行。像这样:

   1 if choice == 'blast':
   2     pete.blast()
   3     pete.blast()
   4     pete.blast()
   5 
   6 pete.write(choice)

So the three blast()s will only happen if the choice is 'blast', but the write will happen no matter what.

上面的三个 blast() 只有当 choice 是 'blast' 时才会被运行,write 无论什么情况都会被运行。

Sometimes, you will want to make a choice between two things:

有时,你希望在两件事情中做出选择:

It can help to make this more clear by reading the word else as "otherwise".

把else 读作 "otherwise" 会帮助我们更容易明白。

   1 choice = 'blast'
   2 if choice == 'blast':
   3     pete.blast()
   4 else:
   5     pete.reset()

There are only two possibilities here, and your program can only flow down one of these two branches.

这里有两种可能,并且你的程序只能通过一条分叉流动。

Other times, you will want to have multiple branches in your flow.

其他时候,你希望在流程中有多个分叉。

Here, the word elif can be read as "else if" or "otherwise if"

这里,单词 elif 可以读作 "else if" 或者 "否则 如果"

   1 choice = 'tree'
   2 if choice == 'blast':
   3     pete.blast()
   4 elif choice == 'tree':
   5     pete.tree()
   6 else:
   7     pete.reset()

You can have as many elif sections as you need. Once any one of the if or elif conditions is True, that section will run and all other elif or else sections will be skipped.

你可以根据你的需要拥有多个 elif 部分。 一旦 if 或者 elif 其中的任何一个的状态是 True 真,那个部分将会被运行并且其他所有的 elif 或者 else 部分将会被跳过。

else is not required, and will only run if none of the preceeding if or elif conditions were True.

else 不是必需的,只有当 if 或者 elif 的结果全部不是 True 真的时候才会运行。