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

标签 python python-2.7

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/

相关文章:

python - 错误 "virtualenv : command not found"但安装位置在 PYTHONPATH 中

macos - 自从在Mac OS X Yosemite上安装python 3以来,ipython Notebook无法启动

python TypeError : argument 1 must be string or read-only character buffer, 不是无

Python 2.7 : Pytz : ImportError: cannot import name timezone

python - pool.map 列表索引超出范围 python

python - 如何在 .csv 文件中转义字符串 Python 2.7 中的逗号

python - 数组 - float64 到数组 - ndarray

python - 尝试输入大数据帧时 Tensorflow 数据集 API 内存错误

python - 将列表中的每个第二个元素替换为其他列表中的每个第三个元素。

python - 将 Pycharm Python 集成到 MySQL CE 数据库的最佳方法是什么?