[英]How do I get a while loop to repeat if input invalid?
我是 python 的新手,正在為 while 循環以及輸入如何決定執行的內容而苦苦掙扎。 這就是我要尋找的:如果用戶輸入無效的國家/地區 ID,則系統會提示他們重試。 如果他們輸入有效的國家/地區 ID,就會喜歡要執行的代碼。 最后,如果他們在提示輸入國家 ID 時輸入“結束”,就像程序結束一樣。 這是我到目前為止所擁有的:
while True:
my_country = input('Enter a valid country: ')
if my_country in unique_countries:
print('Thanks, one moment while we fetch the data')
Some code here
#Exit Program
else:
my_country == "end"
break
我遇到的問題是,正如目前所寫的那樣,如果我輸入一個無效的國家/地區,它會結束程序而不是再次提示我。 先感謝您。 我也是堆棧溢出的新手,對於可怕的格式化感到抱歉。
你需要一個elif
在那里。 試試這個:
while True:
my_country = input('Enter a valid country: ')
if my_country in unique_countries:
print('Thanks, one moment while we fetch the data')
# Some code here
#Exit Program
elif my_country == "end":
break
else:
print ("Try again.")
編輯
使您的 while 循環變為 False。 請遵循以下代碼:
unique_countries = ['India', 'USA', 'Canada', 'Japan']
valid = True
while valid:
my_country = input('Enter a valid country: ')
if my_country in unique_countries:
print('Thanks, one moment while we fetch the data')
# Some code here
valid = False # This will Exit Program
elif my_country == "end":
valid = False
else:
print("Country Name entered is not valid...")
解決這個問題的方法是添加:
if my_country not in unique_countries:
continue
就在您的第一個 if 語句之前。 希望這可以幫助!
給你 go:
while True:
my_country = raw_input('Enter a valid country:')
if my_country in unique_countries:
print('Thanks, one moment while we fetch the data')
break
elif my_country == "end":
break
else:
continue
您可以從編輯代碼
else:
my_country == "end"
break
到 -
elif my_country == "end":
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.