![](/img/trans.png)
[英]How to detect a invalid input and put the user into a loop until an acceptable answer is typed?
[英]How to redo an input if user enters invalid answer
我是編程新手,我想知道如果用戶輸入無效數據,如何重復輸入節。
我希望應用程序僅重復輸入部分,而不是必須重新運行該功能並使用戶再次鍵入所有內容。
我的猜測是,我將不得不將“ 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()
您可以創建一種方法來循環檢查它:
def check_input(values, message):
while True:
x = input(message)
if x in values:
return x
print "invalid values, options are " + str(values)
這是有關控制流的很好的閱讀。
同樣在您的情況下,您可以將strip()
和lower()
用於用戶輸入。
>>> 'HeLLo'.lower()
'hello'
>>> ' hello '.strip()
'hello'
這是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")
您可以泛化代碼以使用消息提示和驗證功能:
def validated_input(prompt, validate):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = validate(value)
return value
例如:
>>> def new_or_used(value):
... return value.lower() in {"new", "used"}
>>> validate_input("New, or used?", new_or_used)
或者,更簡單但不那么靈活地傳遞有效值:
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
並使用:
>>> validate_input("New, or used?", {"new", "used"})
您甚至可以使用有效值來創建輸入提示:
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
提示:
>>> 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.