Exercise 35: 分支和函数

来源:互联网 发布:淘宝店怎么经营视频 编辑:程序博客网 时间:2024/05/06 10:04

原文链接:http://learnpythonthehardway.org/book/ex35.html

        你现在已经学习过了 if 语句,函数和列表。现在是时候考验下你了,输入下面这个实例,看看你是否能够弄明白它做了什么。

from sys import exitdef gold_room():print "This room is full of gold. How much do you take?"next = raw_input("> ")if "0" in next or "1" in next:how_much = int(next)else:dead("Man ,learn to type a number.")if how_much < 50:print "Nice ,you're not greedy ,you win!"exit(0)else:dead("You greedy bastard!")def bear_room():print "There is a bear here."print "The bear has a bunch of honey."print "The fat bear is in front of another door."print "How are you going to move the bear?"bear_moved = Falsewhile True:next = raw_input("> ")if next == "take honey":dead("The bear looks at you then slaps your face off.")elif next == "taunt bear" and not bear_moved:print "The bear has moved from the door. You can go through it now."bear_moved = Trueelif next == "taunt bear" and bear_moved:dead("The bear gets pissed off and chews your leg off.")elif next == "open door" and bear_moved:gold_room()else:print "I got no idea what that means."def cthulhu_room():print "Here you see the great evil Cthulhu."print "He ,it ,whatever stares at you and you go insane."print "Do you flee for your life or eat your head?"next = raw_input("> ")if "flee" in next:start()elif "head" in next:dead("Well that was tasty!")else:cthulhu_room()def dead(why):print why ,"Good job!"exit(0)def start():print "You are in a dark room."print "There is a door to your right and left."print "Which one do you take?"next = raw_input("> ")if next == "left":bear_room()elif next == "right":cthulhu_room()else:dead("You stumble around the room until you starve.")start()

输出结果如下:

下面就是我玩这个游戏的结果:
E:\>python ex35.pyYou are in a dark room.There is a door to your right and left.Which one do you take?> leftThere is a bear here.The bear has a bunch of honey.The fat bear is in front of another door.How are you going to move the bear?> taunt bearThe bear has moved from the door. You can go through it now.> open doorThis room is full of gold. How much do you take?> 1000You greedy bastard! Good job!

研究训练:

1、为这个游戏画一个路线图,看看怎样才能通过这个游戏。
2、修复你脚本中的所有错误,包括拼写错误。
3、对你不理解的函数写好注释,还记得文档注释吗?
4、向游戏中添加更多的游戏情节,怎样做才能既简洁又可以很好的扩展游戏呢?
5、这个 gold_room 游戏使用了奇怪的方式让你键入一个数字。这种方式会导致什么样的 bug? 你可以用比检查 0、1 更好的方式判断输入是否是数字吗?int() 这个函数可以给你一些头绪。

学生遇见的常见问题:

求救!这个程序到底是怎么工作的啊?

答:任何时候在你理解一段代码遇到困难时,你只要简单的为每一行代码写上注释解释它们都做了什么。当你在做这个操作的时候,你得记住以前正确的注释在新的环境和信息下就不一定正确了。接着你就可以试着画一个工作示意图或者写一两段来描述它是如何工作的,这样你就能弄明白了。

为什么使用 while True: ?

答:用于创建一个无限循环操作。

exit(0) 做了什么操作?

答:在很多操作系统中exit(0) 可以用来终止正在运行的项目,并且其中传递的数值可以指明程序是否发生错误。如果你用 exit(1) 就表明出现了一个错误,而 exit(0)就表示正常退出。至于原因你得回到之前学过的布尔逻辑表达式(0 == False),你可以用不同的值来表明不一样的错误结果。你可以用exit(100)来代表一个不同于exit(1)或者exit(0)的错误结果。

为什么 raw_input() 有时候写作 raw_input('> ‘)?

答:raw_input中的参数是一个字符串,用来在获取用户输入之前作为一个提示符而打印出来的。

0 0
原创粉丝点击