简体   繁体   English

字典和循环

[英]Dictionaries and Loops

I have created a simple dictionary with some countries and their populations.我用一些国家和他们的人口创建了一个简单的字典。 Further, I added code for user to input a country and if that is a match, code should return the population from dictionary defined.此外,我为用户添加了代码以输入一个国家,如果匹配,代码应该从定义的字典中返回人口。 This is done until user inputs '0'.这样做直到用户输入“0”。 Here is my question now: I am looking to further have the program display a message to user that population is unknown in case the country is not part of the dictionary and have the user enter the population in that case.这是我现在的问题:我希望进一步让程序向用户显示一条消息,指出人口未知,以防国家不属于字典的一部分,并且在这种情况下让用户输入人口。 For example, if user input is Seychelles, I should get an Unknown message and a prompt to enter population.例如,如果用户输入的是塞舌尔,我应该收到一条未知消息和输入人口的提示。 Finally, I want to update the dictionary with these new values for country (Seychelles in my example) and population entered.最后,我想用输入的国家(在我的示例中为塞舌尔)和人口的这些新值更新字典。

My code so far is到目前为止我的代码是

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()

Basically all you need to add is a elif ctry not in countryPop: to check if the dictionary contains input country.基本上,您需要添加的是一个elif ctry not in countryPop:elif ctry not in countryPop:检查字典是否包含输入国家/地区。 and if not read the population input and write something like countryPop[ctry]=popIn to update the dictionary.如果没有读取人口输入并写一些类似countryPop[ctry]=popIn来更新字典。

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

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