如何清除或覆盖python中错误的用户输入

时间:2019-01-24 13:42:19

标签: python python-3.x

我正在编写一个脚本,该脚本在多个点上接受用户输入。如果输入正确,则我需要跳出循环并继续。但是,如果这是错误的,我想做的就是删除并重新提示输入。这是我正在努力的一般情况:

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

我一直在做一些研究,但还没有发现对我有意义的东西。有没有一种方法可以删除或覆盖用户输入的值,以便再次输入测试后,它是一个全新的值?

3 个答案:

答案 0 :(得分:2)

如果这对于您在再次要求用户输入之前清除屏幕非常重要,则可以在显示错误消息之后等待一段时间,然后再次要求用户清除错误消息。

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)

如果您想清除错误消息和以前的输入,可以使用例如os.system('clear')

答案 1 :(得分:1)

solution:

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

您不必在重新提示时“清除”测试,因此每次都可以更改测试的值

答案 2 :(得分:0)

为什么不做这样的事情

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

希望有帮助