Python“if”计算“and”的两侧?

2024-09-27 04:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

有谁能告诉我为什么以下失败了:

teststr = "foo"
if not teststr.isdigit() and int(teststr) != 1:
   pass

使用:

ValueError: invalid literal for int() with base 10: 'foo'

在C中,如果&&测试中的第一部分失败,则不再计算右侧。这在Python中不同吗?你知道吗

编辑:我太蠢了。当然,and应该是一个or。。。。。你知道吗


Tags: and编辑forbaseiffoowithnot
3条回答

if not teststr.isdigit()是真的,因此它需要计算int(teststr)来完成and的需求—因此是异常。你知道吗

不要预先检查数据,而是使用EAFP-并使用以下内容。。。你知道吗

try:
    val = int(teststr)
    if val != 1:
        raise ValueError("wasn't equal to 1")
except (ValueError, TypeError) as e:
    pass # wasn't the right format, or not equal to one - so handle
# carry on here...

not teststr.isdigit()是真的,所以第一个测试不会失败。你知道吗

if not teststr.isdigit() and int(teststr) != 1:

评估为

if ((not teststr.isdigit()) and (int(teststr) != 1)):

好吧,但是teststr不是数字,所以isdigit()是假的,所以(not isdigit())是真的。对于True and B,您必须计算B。这就是为什么它尝试将类型转换为int

相关问题 更多 >

    热门问题