笨方法学python:练习35
习题 35: 分支和函数
你已经学会了 if 语句、函数、还有列表。现在你要练习扭转一下思维了。把下
面的代码写下来,看你是否能弄懂它实现的是什么功能。
代码:



运行结果:

加分习题
1. 把这个游戏的地图画出来,把自己的路线也画出来。 哈哈,这个我画了,但是不会写出来的。
2. 改正你所有的错误,包括拼写错误。
3. 为你不懂的函数写注解。记得文档注解该怎么写吗?

使用“”“..."""给定义的函数写注释,说明这个函数的作用就好了。
有关bear_room()函数:
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 = False
while 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 = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your legs off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
第一次看这个函数的时候,也没有看懂,然后网上的答案也没有很对症状。现在附上本人的理解:
while true:的使用,表示这一段无限循环(为什么?自己搜)
当你输入take honey时,会转跳到函数dead("The bear looks at you then slaps your face off."),转跳以后离开这个循环(注意!!!);
当你输入taunt bear时,elif next == "taunt bear" and not bear_moved:的条件为真,故执行
print "The bear has moved from the door. You can go through it now."
bear_moved = True
注意,此时并不会执行elif next == "taunt bear" and bear_moved:下的函数
dead("The bear gets pissed off and chews your legs off.")
因为bear_moved = False,条件next == "taunt bear" and bear_moved为假。
第一次输入taunt bear后,有两种情况:
1)循环继续执行,再次输入taunt bear时,bear_moved = True, 条件next == "taunt bear" and bear_moved为真,转调到函数 dead("The bear gets pissed off and chews your legs off.")
2)循环继续执行,输入open door,bear_moved = True, 条件next == "open door" and bear_moved为真,转跳到函数gold_room()
4. 为游戏添加更多元素。通过怎样的方式可以简化并且扩展游戏的功能呢?
5. 这个 gold_room 游戏使用了奇怪的方式让你键入一个数字。这种方式会导致什么
样的 bug? 你可以用比检查 0、 1 更好的方式判断输入是否是数字吗? int() 这
个函数可以给你一些头绪。

使用isdigit()函数可以判定是否为数字。
笔记:
1) exit()函数
exit(0):无错误退出 exit(1):有错误退出 退出代码是告诉解释器的(或操作系统)
2) isdigit()函数
-------------------------------------------- s为字符串 s.isalnum() 所有字符都是数字或者字母 s.isalpha() 所有字符都是字母 s.isdigit() 所有字符都是数字 s.islower() 所有字符都是小写 s.isupper() 所有字符都是大写 s.istitle() 所有单词都是首字母大写,像标题 s.isspace() 所有字符都是空白字符、\t、\n、\r