5

我正在尝试使用 Walrus 运算符从用户那里获取输入:=,但如果用户只键入Enter密钥 as input,则 python 脚本将终止。如何捕获此错误并确保用户不仅按下了Enter键?

这个答案,但使用海象运算符不起作用。

没有海象运算符的这段代码将成功检查是否不仅按下了Enter键:

while True:
    answer = input("Please enter something: ")
    if answer == "":
        print("Invalid! Enter key was pressed.")
        continue
    else:
        print("Enter wasn't pressed!")
        # do something

如果用户只按Enter,则整个脚本将终止。

while answer := input("Please enter something: "):
    # if user pressed only `Enter` script will terminate. following will never run
    if answer == "":
        print("enter was pressed")
    else:
        print("Enter wasn't pressed!")
        # do something
4

3 回答 3

2

代码中发生了什么?

第1部分:

发生这种情况是因为该语句answer := input("Please enter something: ")获取输入值并分配给变量answer。如果按下Enter,则值为answer空字符串。

第 2 部分:
while循环评估值。由于该值为空字符串并且空字符串评估为 false,因此循环退出

我们不能使用海象运算符来执行此操作,因为控件永远不会进入循环内部,而且您想检查输入字符串的值

于 2020-07-16T00:49:04.223 回答
1

您将赋值表达式放在错误的位置。您的原始循环是无限的,但您的第二个循环answer用作中断条件。

while True:
    if not (answer := input("Type something: ")):
        print("You didn't type anything before pressing Enter!")
        continue
    print("You typed:", answer)

同样,由于我们使用的是 ,因此不需要continue该子句。else

在行动:

Type something: hello!
You typed: hello!
Type something:
You didn't type anything before pressing Enter!
Type something: hi!
You typed: hi!

但是,在这里使用海象运算符并没有真正的优势,所以我会避免它。

while True:
    answer = input("Type something: ")
    if not answer:
        print("You didn't type anything before pressing Enter!")
        continue
    print("You typed:", answer)
于 2020-07-16T01:55:32.400 回答
-1

您可以编写以下代码:

while (answer := input("Please enter something: ")) != 0:
    # if user pressed only `Enter` script will terminate. following will never run
    if answer == "":
        print("enter was pressed")
    else:
        print("Enter wasn't pressed!")
        # do something

这意味着 != 0 将始终得到满足。

于 2020-07-16T00:55:03.170 回答