虽然不是假的

While not False

提问人:Dev_Michael 提问时间:8/26/2021 最后编辑:NeuronDev_Michael 更新时间:8/26/2021 访问量:2752

问:

因此,我需要一个代码来捕捉一个人输入字符串而不是数字,并继续要求该人输入有效数字。

所以我在网上找到了这个对我的代码的修复,虽然它有效,但我仍然不明白它为什么有效

我理解其中的大部分内容,值设置为但是;False

为什么 Even 首先会循环?while not false

究竟是什么让循环保持运行?


代码片段如下:

def repeat():
    correct_value = False
    while not correct_value:
        try:
            guess = int(input())
        except ValueError:
            print("Please Enter a Number")
        else:
            correct_value = True
    return guess
python while-loop 布尔逻辑

评论

1赞 8/26/2021
因为计算结果为 .检查文档中的.它指出:如果运算符的参数为 false,则运算符生成 True,否则为 False。not FalseTruenotnot

答:

0赞 varisha15 8/26/2021 #1

不是 False 意味着 True,这就是它首先起作用的原因。 特殊处理用于此类目的。它尝试接受整数输入,如果用户不输入整数,则会抛出由 except 块处理的错误。

如果用户确实给出了一个整数,则 correct_value 变为 true,因此 Not True 表示 false,因此循环终止并且函数返回输入。

0赞 BWallDev 8/26/2021 #2

not False 表示 True。关键字“not”否定 True 到 False,反之亦然。与“while True”循环不同,“while False”循环将被跳过。看看这段代码,看看我的意思:

exit = False

while exit:
    print('In while loop')
    break

while not exit:
    print('In 2nd while loop')
    break;

print('End')

输出:

In 2nd while loop
End
1赞 Marcel 8/26/2021 #3

看看下面的代码:

def repeat():
    correct_value = False

    # while not False so the correct_value = True
    # so it is an equivalent of -> while True:
    # while True will always run
    while not correct_value:
        try:
            guess = int(input())
        except ValueError:
            print("Please Enter a Number")
        else:
            correct_value = True
    return guess

为什么“虽然不是假的”甚至首先循环?
它循环是因为总是 .
True

真正保持循环运行的实际情况是什么?
完全相同,这导致
while not Falsewhile True

0赞 AbyxDev 8/26/2021 #4

为了补充其他答案,你也可以这样想:在英语中,“不正确”的意思是“不正确”。因此,“虽然不正确”的意思是“虽然不正确”——即当输入仍然不正确时。

就像“正确”的反义词是“不正确”一样,反义词是.FalseTrue

您可以像以下方式一样轻松地编写代码:

def repeat():
    incorrect_value = True # assume incorrect so that loop will run at all
    while incorrect_value:
        try:
            guess = int(input())
        except ValueError:
            print("Please Enter a Number")
        else:
            incorrect_value = False # stop the loop next time the condition is checked
    return guess