0

I'm writing a script that takes in user input at multiple points. If the input is correct, all I need is to break out of the loop and continue. But if it's wrong, what I'm trying to do is delete and then re-prompt for that input. Here is a general case of what I'm working towards:

while True:
   test = input("Enter test to check: ")
   if test == expected:
      break
   else:
      print("Error: test is incorrect")
      #Clear/overwrite test
      #Re-prompt for input

I've been doing some research but I haven't found anything that really makes sense to me. Is there a way to delete or overwrite the value entered by the user so that once test is entered again, it's an entirely new value?

1
  • I see nothing wrong with that code. You can add test=None after the else if for some reason you want to "destroy" the user input. Commented Jan 24, 2019 at 13:48

3 Answers 3

2

If that's very important to you to clear the screen before asking user again for input you could wait some time after displaying error message and then ask user for input again wiping out error message.

import time
expected = 'foo'

while True:
    print(' '*30 + '\r', end='')
    test = input("Enter test to check: ")
    if test == expected:
        break
    else:
        print("Error: {} is incorrect\r".format(test), end='')
        time.sleep(2)

If you would like to clear error message and previous input you could use for example os.system('clear').

Sign up to request clarification or add additional context in comments.

2 Comments

I don't necessarily need to clear the screen, I already tried using os.system('clear'). I just need to overwrite or clear the value within test so that if a wrong input is entered, the new input isn't concatenated onto the old input
input() is just an function and value entered by user isn't going to modify it. If you want to save all inputs entered by user store them into a list, so that new inputs won't overwrite older ones.
1
solution:

else:
    print("Error: test is incorrect")
    test = input("Enter test to check")

You don't have to 'clear' test as you're reprompting and therefore changing the value of test each time

2 Comments

But wouldn't adding another test = input("Enter test to check") have two input prompts should a wrong value be entered?
No, it should just loop back to the original input prompt until a valid input for test is entered. As the variable name is the same it shouldn't ask twice
0

Why not do something like this

lol=True
while lol:
   test = input("Enter test to check: ")
   if test == expected:
      lol=False
      print("Corect!!!")
   else:   
      print("Error: test is incorrect")

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.