简体   繁体   中英

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'. 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. and if not read the population input and write something like countryPop[ctry]=popIn to update the dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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