【问题标题】:Dictionaries and Loops字典和循环
【发布时间】:2020-01-27 04:24:32
【问题描述】:

我创建了一个包含一些国家及其人口的简单字典。此外,我为用户添加了输入国家/地区的代码,如果匹配,代码应该从定义的字典中返回人口。这一直进行到用户输入“0”。现在这是我的问题:我希望进一步让程序向用户显示人口未知的消息,以防该国家/地区不在字典中,并让用户在这种情况下输入人口。例如,如果用户输入是 Seychelles,我应该会收到一条未知消息和输入人口的提示。最后,我想用这些新的国家值(在我的例子中是塞舌尔)和输入的人口来更新字典。

到目前为止我的代码是

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

【问题讨论】:

    标签: python loops dictionary input


    【解决方案1】:
    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: 来检查字典是否包含输入国家/地区。如果不读取人口输入并编写类似countryPop[ctry]=popIn 的内容来更新字典。

    【讨论】:

    • 谢谢。效果很好,我添加输出以显示附加的字典
    • @meag_a 如果这回答了您的问题,请务必将其标记为此类。很高兴我能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2018-07-13
    • 2013-11-12
    • 2017-07-21
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多