[英]How to redo an input if user enters invalid answer
I'm new to programming, and I was wondering how I can repeat an input section, if the user types in invalid data. 我是编程新手,我想知道如果用户输入无效数据,如何重复输入节。
I want the application to just repeat the input section, instead of having to run the function all over again and making the user type everything all over again. 我希望应用程序仅重复输入部分,而不是必须重新运行该功能并使用户再次键入所有内容。
My guess is that I would have to change the "return main()" into something else. 我的猜测是,我将不得不将“ return main()”更改为其他内容。
condition = input("What is the condition of the phone(New or Used)?")
if condition not in ["New", "new", "Used", "used"]:
print("Invalid input")
return main()
gps = input("Does the phone have gps(Yes or No)?")
if gps not in ["Yes", "yes", "No", "no"]:
print("Invalid input")
return main()
You can make a method to check it in a loop: 您可以创建一种方法来循环检查它:
def check_input(values, message):
while True:
x = input(message)
if x in values:
return x
print "invalid values, options are " + str(values)
Here is a good reading about Control Flows . 这是有关控制流的很好的阅读。
Also in your case, you can use strip()
and lower()
for user inputs. 同样在您的情况下,您可以将strip()
和lower()
用于用户输入。
>>> 'HeLLo'.lower()
'hello'
>>> ' hello '.strip()
'hello'
Here is the solution for Python 3: 这是Python 3的解决方案:
while True:
condition=input("What is the condition of the phone(New or Used)?")
if condition.strip().lower() in ['new', 'used']:
break
print("Invalid input")
while True:
gps=input("Does the phone have gps(Yes or No)?")
if gps.strip().lower() in ['yes','no']:
break
print("Invalid input")
You can generalise the code to use a message prompt and a validating function: 您可以泛化代码以使用消息提示和验证功能:
def validated_input(prompt, validate):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = validate(value)
return value
eg: 例如:
>>> def new_or_used(value):
... return value.lower() in {"new", "used"}
>>> validate_input("New, or used?", new_or_used)
Or, simpler, but less flexible, pass in the valid values: 或者,更简单但不那么灵活地传递有效值:
def validated_input(prompt, valid_values):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = value.lower() in valid_values
return value
And use: 并使用:
>>> validate_input("New, or used?", {"new", "used"})
You could even use the valid values to create the input prompt: 您甚至可以使用有效值来创建输入提示:
def validated_input(prompt, valid_values):
valid_input = False
while not valid_input:
value = input(prompt + ': ' + '/'.join(valid_values))
valid_input = value.lower() in valid_values
return value
Which gives a prompt: 提示:
>>> validate_input("What is the condition of the phone?", {"new", "used"})
What is the condition of the phone?: new/used
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.