I'm trying to get input from a user using the Walrus operator :=
, but if the user will only type in the Enter key as input
, than the python script will terminate. How can I catch this error and make sure that the user hasn't only pressed the Enter key?
There is this answer but it does not work using the walrus operator.
This code without the walrus operator will successfully check that not only the Enter key was pressed:
while True:
answer = input("Please enter something: ")
if answer == "":
print("Invalid! Enter key was pressed.")
continue
else:
print("Enter wasn't pressed!")
# do something
If the user only presses Enter, than the whole script will terminate.
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