简体   繁体   English

如何放置一个循环,要求用户一次又一次地输入直到输入正确的国家/地区

[英]how to put a loop that asks user again and again to input till it enters correct country

how to put a loop that asks user again and again to input till it enters correct country如何放置一个循环,要求用户一次又一次地输入直到输入正确的国家/地区

population ={
    'china': '143',
    'india': '136',
    'usa': '32',
    'pakistan': '21'
}
population['bhutan'] = 2

print(population['china'])


country = input("enter countri name-")
country.lower()
if country in population:
    print(f"population {country} is: {population[country]} crore")
else:
   print("input again")
   country = input("enter countri name-")

if country in population:
    print(f"population {country} is: {population[country]} crore")
else:
   print("input again")

One way to do is with a while true that check if the input is correct using the break keyword that will stop the loop一种方法是使用 while true 检查输入是否正确,使用 break 关键字来停止循环

while True:
   country = input("enter countri name-")
   if country in population:
        break;
    

Or even do something like this that is more pythonic或者甚至做这样更像 pythonic 的事情

country = input("enter countri name-")
while country not in population:
   country = input("Enter valid country")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM