我正在尝试使用 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