Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Python program that will read in the countries and their capitals from t

ID: 3730653 • Letter: W

Question

Write a Python program that will read in the countries and their capitals from the countryCap.txt file. Look at the file. It is a comma-delimited file (comma between country and capital). You will need to get a line from the .txt file, split the line into a country and a capital (remember that the split method returns a list) and then store them in a dictionary. (As you recall from Chapter 8, a dictionary has a key/value pair. The key can be the country name, and the value can be the capital name.) Once all data from the text file has been stored in the dictionary, allow the user to enter the name of a country, then find the capital and display it to the user. Loop back up and let them enter another country until they enter a value of ‘x’ to stop the loop.
Make sure to handle the following exceptions …if the user’s country name is not found in the dictionary, or if the countryCap.txt file is not found when you try to open it.
You will need to create two functions … one called fillDictionary() and one called findCapital(). Pass the appropriate data using a parameter list. Do not use global variables.

Explanation / Answer

def fillDictionary(): d = {} try: with open('countryCap.txt', 'r') as f: for line in f: words = line.strip().split(",") d[words[0]] = words[1] except: print('countryCap.txt is not found') return d def findCapital(d, country): if country in d: print('capital of ' + country + ' is ' + d[country]) else: print('capital for ' + country + ' is not found') def main(): d = fillDictionary() while True: name = input('Enter country name(x to exit): ') if name == 'x': break findCapital(d, name) main()

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote