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

Exercise 31:做出决定

2014-03-31 17:41 211 查看
原文链接:http://learnpythonthehardway.org/book/ex31.html

       这本书的上半部分你打印了一些东西,而且调用了函数,不过一切都是直线式进行的。你的脚本从顶部开始运行一直运行到代码底部结束。如果你创建了一个函数你可以在之后调用它运行,但这种形式始终不是一种真正的分支结构,不能让你真正的做出不同的决定。现在你有了 if ,else 和 elif 你就可以开始让你的脚本真正的决定哪些执行哪些不执行了。

       在上一次的脚本中你写了一组简单的提问测试。在这次的脚本中你需要询问用户问题,并且根据用户的回答做出决定。把脚本写下来,多多鼓捣一阵子,看看它的工作原理是什么。

print "You enter a dark room with two doors. Do you go through door #1 or door #2"

door = raw_input("> ")

if door == "1":
print "There's a giant bear eating a cheese cake. What do you do?"
print "1.Take the cake."
print "2.Scream at the bear."

bear = raw_input("> ")

if bear == "1":
print "The bear eats your face off. Good job!"
elif bear == "2":
print "The bear eats your legs off. Good job!."
else:
print "Well,doing %s is probably better. Bear runs away." % bear

elif door == "2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1. Blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."

insanity = raw_input("> ")

if insanity == "1" or insanity == "2" :
print "Your body survives  powered by a mind of jello. Good job!"
else:
print "The insanity rots your eyes into a pool of muck. Good job!"

else:
print "You stumble around and fall on a knife and die. Good job!"
      这里最主要的就是你可以将一个if语句放在另一个if语句中运行。这是一个很强大的功能,可以用来创建嵌套(nested)的决定,其中的一个分支将引向另一个分支的子分支。

   
b3ab
  确保你理解了if语句嵌套的概念。事实上,做一下研究训练你就可以确认你自自己是否真的掌握了它。

输出结果如下:

c:\>python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2
> 1
There's a giant bear eating a cheese cake. What do you do?
1.Take the cake.
2.Scream at the bear.
> 2
The bear eats your legs off. Good job!.

研究训练:

为游戏添加新的部分,改变玩家做决定的位置。尽自己的能力扩展这个游戏,不过别把游戏弄得太怪异了。

学生遇见的常见问题:

可以用一组if/else来替代 elif 吗?

答:在一些情况写是可以的,它取决于你没有给if/else是怎么写的。如果替换的话也就意味着Python需要去检查每一个if/else组合,而不仅仅像if/elif/else这样的只需要检查一组。(ps:这里有可能翻译不准。)你可以尝试一下找出它们的不同之处。

我怎么表示一个数值变量在某个数值范围内?

答:你有两个选择:使用 0 < x < 10 或者 1 <= x < 10,这是比较基础的用法,或者你可以使用 x in range(1 ,10) 。

如果我想在 if/elif/else 代码块添加更多选项应该怎么做?

答:简单,只要为每一种可能的选择添加更多的 elif 代码块就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python elif else if