How to check if the Enter key was pressed while using the Walrus operator in Python?

1.5k Views Asked by At

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
3

There are 3 best solutions below

0
On BEST ANSWER

You put the assignment expression in the wrong spot. Your original loop is infinite, but your second loop uses answer as the break condition.

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

As well, since we're using continue, the else clause is not needed.

In action:

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

However, there's no real advantage to using the walrus operator here, so I would avoid it.

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

You can write the following code:

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

This means that != 0 will always be satisfied.

0
On

What's happening in the code?

Part 1:

This happens because this statement answer := input("Please enter something: ") takes the input value and assigns to the variable answer. If you press Enter then the value for answer is empty string.

Part 2:
while loop evaluates the value. As the value is an empty string and empty string evaulates to false, the loop exits

We can't do this using walrus operator because the control never goes inside the loop and moreover you want to check the value of the entered string