我已经声明了'started'=False,在嵌套的if条件中,打印的结果与我预期的相反

I've declared 'started'=False where in the nested if condition the printed results are inversed to what I expected

提问人: 提问时间:5/3/2021 最后编辑:James Z 更新时间:5/3/2021 访问量:29

问:

started=False
while True:
    command=input("Enter your command: ").lower()
    if command=='start':
        if started:
            print("Car is has successfully started. Engines on!")
        else:
            started=True
            print("Car has already started!")
    
    else:
        print("Enter correct command")

在这里,我向您介绍了我卡住的程序部分。假设在嵌套循环中,如果变量 'started' 是 false(因为它被设置),它应该打印第一个 print 语句,但它没有。它以某种方式打印 else print 语句。基本上,结果反转为我想要的。我的布尔逻辑错了。请详细解释为什么会发生这种情况。

python-3.x 布尔逻辑

评论

0赞 12944qwerty 5/3/2021
顺便说一句,这不是一个嵌套循环,你被困在哪个 if 语句上?
0赞 Vivek Anand 5/3/2021
因为当你的值是'False'时,你需要评估,你应该使用操作器。那是ifTruestartednotif not started:
1赞 Axe319 5/3/2021
你只是把你的陈述弄混了。 你想让它读.切换您的语句,它将按预期工作。printif started:"Car has already started!"print

答: 暂无答案