Search code examples
pythonpython-3.xwalrus-operator

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


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

Solution

  • 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)