gpt4 book ai didi

python - 艰难地学习 Python - 练习 36 - if else die 函数

转载 作者:行者123 更新时间:2023-11-28 22:37:33 32 4
gpt4 key购买 nike

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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com