[英]Dictionaries and Loops
我用一些国家和他们的人口创建了一个简单的字典。 此外,我为用户添加了代码以输入一个国家,如果匹配,代码应该从定义的字典中返回人口。 这样做直到用户输入“0”。 这是我现在的问题:我希望进一步让程序向用户显示一条消息,指出人口未知,以防国家不属于字典的一部分,并且在这种情况下让用户输入人口。 例如,如果用户输入的是塞舌尔,我应该收到一条未知消息和输入人口的提示。 最后,我想用输入的国家(在我的示例中为塞舌尔)和人口的这些新值更新字典。
到目前为止我的代码是
def main():
countryPop = {'Vatican': 800, 'Tuvalu': 10200, 'Nauru': 11000, 'Palau': 17900,
'San Marino': 33420, 'Monaco': 38300, 'Marshall Islands': 55500}
while True:
ctry = input('Enter country:')
population = countryPop.get(ctry)
print(population)
if ctry == '0':
break
if __name__ == '__main__':
main()
def main():
countryPop = {'Vatican': 800, 'Tuvalu': 10200, 'Nauru': 11000, 'Palau': 17900,
'San Marino': 33420, 'Monaco': 38300, 'Marshall Islands': 55500}
while True:
ctry = input('Enter country:')
population = countryPop.get(ctry)
print(population)
if ctry == '0':
break
elif ctry not in countryPop: #check if country is in dictionary
popIn = input("Country Pop: ") #read country population
countryPop[ctry]=popIn #update dictionary
if __name__ == '__main__':
main()
基本上,您需要添加的是一个elif ctry not in countryPop:
的elif ctry not in countryPop:
检查字典是否包含输入国家/地区。 如果没有读取人口输入并写一些类似countryPop[ctry]=popIn
来更新字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.