这里的“while”条件有什么问题?

-1 python while-loop

这里的 while 条件有什么问题

while (a = input(">").lower()) != "quit":
    if a == "start":
        print("Car started...Ready to go")
    elif a == "stop":
        print("Car stopped")
Run Code Online (Sandbox Code Playgroud)

小智 5

在 python 中不能以这种方式赋值。如果您使用的是 python 3.8 或更高版本,您可以使用所谓的walrus 运算符,如下所示:

while (a := input(">").lower()) != "quit":
    if a == "start":
        print("Car started...Ready to go")
    elif a == "stop":
        print("Car stopped")
Run Code Online (Sandbox Code Playgroud)

否则你需要做这样的事情:

a = input(">").lower()
while a != "quit":
    if a == "start":
        print("Car started...Ready to go")
    elif a == "stop":
        print("Car stopped")
    a = input(">").lower()
Run Code Online (Sandbox Code Playgroud)