【问题标题】:how do you test an expression without it running?如何在不运行的情况下测试表达式?
【发布时间】:2021-09-06 16:49:34
【问题描述】:

有没有办法测试表达式是否导致错误 没有正常运行(这会导致程序崩溃)? 特别是,在不知道temp[1] 是否为数字的情况下,块int(temp[1])(如“10”或“142”等字符串数字)?我尝试这样做的原因是实现涉及用户输入的错误处理。

【问题讨论】:

  • 期望的概念是在它们发生时处理它们。试图提前阻止它们可能会导致竞争条件和其他问题。

标签: python user-interface typeconverter


【解决方案1】:

您可以使用type(temp[1]) 或isinstance(temp[1], int) 来检查类型。要专门检查字符串是否为数字,请使用temp[1].isdigit()。

【讨论】:

    【解决方案2】:

    你可以试试if isinstance(temp[1], int)。这会检查 temp[1] 是否是 int 类的实例。

    另一种方法是捕获错误本身。这样你就知道它会导致错误。例如:

    try:
        int(temp[1])
    except ValueError:
        print("The variable temp[1] can't be changed to an int.")
    

    【讨论】:

    • 为什么不写if type(temp[1]) is int,或者更好的if isinstance(temp[1], int)?使用type(0) 对我来说似乎有点神秘。注意:在 Python 中并不真正推荐比较类型。恕我直言,您的“尝试除外”解决方案要好得多。虽然可能有理由专门检查某种类型,但从问题中并不清楚。
    • @wovano 好点。你是对的:if type(temp[1]) == type(int) 是有点矫枉过正。以后会记住的!
    猜你喜欢
    • 2011-06-13
    • 2019-09-23
    • 2014-10-04
    • 2022-10-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多