Men*_*elG 5 python python-3.x walrus-operator
我正在尝试使用 Walrus operator 获取用户的输入:=,但如果用户只输入Enter密钥 as input,则 python 脚本将终止。如何捕获此错误并确保用户不仅按下了Enter键?
有这个答案,但它不适用于海象运算符。
这段没有 walrus 运算符的代码将成功检查是否不仅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
Run Code Online (Sandbox Code Playgroud)
如果用户只按下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
Run Code Online (Sandbox Code Playgroud)
您将赋值表达式放在了错误的位置。您的原始循环是无限的,但您的第二个循环用作answer中断条件。
while True:
if not (answer := input("Type something: ")):
print("You didn't type anything before pressing Enter!")
continue
print("You typed:", answer)
Run Code Online (Sandbox Code Playgroud)
同样,由于我们使用的是continue,else因此不需要该子句。
行动中:
while True:
if not (answer := input("Type something: ")):
print("You didn't type anything before pressing Enter!")
continue
print("You typed:", answer)
Run Code Online (Sandbox Code Playgroud)
然而,在这里使用 walrus 运算符没有真正的优势,所以我会避免它。
while True:
answer = input("Type something: ")
if not answer:
print("You didn't type anything before pressing Enter!")
continue
print("You typed:", answer)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
269 次 |
| 最近记录: |