If 语句的第二条规则 here ,这让我感到困惑的是:
If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
这是上一个练习的代码:
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?"
choice = raw_input("> ")
if choice == ‘left’:
bear_room()
else:
dead(‘You stumble around the room until you starve.’)
本质上是说如果不满足条件,则必须成功终止程序吗?
最佳答案
是的,这个想法是:
import sys
def die(msg):
print msg
sys.exit(1)
if condition:
# do stuff
else:
die('This cannot happen!')
您还可以使用 assert
来代替,或者引发异常,或者任何其他会导致灾难性失败的事情。这可以帮助您在运行时验证您不希望执行的子句确实没有运行。
恕我直言,您不应该太关注这个die
到底是如何完成的。所引用的文本试图表达的重要一点是,当您确定某些条件为真时,您不妨强制断言它,以便您可以捕获运行时错误。
关于python - 艰难地学习 Python - 练习 36 - if else die 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36432098/