习题 31: 作出决定
目标与感悟:
•符号不能混用,制表符和4个空格两者只能同时使用一个(同一种功能时)。
•知晓if语句的使用,理论上可以无限嵌套。
•嵌套,我理解就跟树的分支一样。
•if语句只返回为Ture的第一个区块,如果一直没有符合的将会结束操作,所以,想法一定要完善。
ex31.py
#-*- coding:utf-8-*-
print "You enter a dark room with two doors. Do you go throuth door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here 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!"
运行结果:
很奇怪,出错了`````````````
看语法结构什么的好像也没什么问题,报错的内容即缩进对应级别不匹配,就是可能多加了什么括号之类.
后来打开notepad显示空格和制表符
看起来都是4个空格距离,但符号不一样就是不一样,应该是制表符(TAB键),修改完毕后则正常了。
正确输出结果:
ex31.py
下面测试一个简单三层嵌套:
ex31_1.py
#-*- coding:utf-8-*-
print "Enter one number (1-10),please."
a = raw_input("> ")
if a == "1":
print "1. Take the cake."
print "2. ET is very interesting!"
print "3. Scream at the bear."
b = raw_input("> ")
if b == "1":
print "Yeah ,cake is vert delicious!What kind of cake do you like?"
print "1. apple cake."
print "2. banana cake."
print "3. orange cake."
c = raw_input("> ")
if c == "1":
print "Yeah,apple cake is vert delicious!"
else:
print "You stumble around and fall on a knife and die. Good job!"
运行结果: