Good!
But if the user keeps with a nonexistent country more than 12 times the script exits with no result at all. Because of the for loop. It loops 12 times only. Also, both lists ( 'countries' and 'capitals' ) are created but never used. However, the script works.
Slightly different approach:
But if the user keeps with a nonexistent country more than 12 times the script exits with no result at all. Because of the for loop. It loops 12 times only. Also, both lists ( 'countries' and 'capitals' ) are created but never used. However, the script works.
Slightly different approach:
print("No.\tCountries\t\t\t Capitals\n ") f = open(r'C:\Users\USER\Desktop\Notepad_Read\countries.txt') count = 0 data = f.readlines() countries = [] #Empty list capitals = [] #Empty list for line in data: line = line.rstrip('\n') ciuntry, capital = line.split(',') countries.append(country) #Country are stored in countries list capitals.append(capital) #Capital are stored in capitals list count = count + 1 print("{0:2}\t{1:26}\t {2:24}".format(count,country,capital)) while True: # it loops until 'x' or the right county ctry = input("Enter a country name (x to Exit): ") if ctry == 'x' or ctry == 'X': break elif ctry.title() in countries: i = countries.index(ctry.title()) # get the corresponding index print ("The capital of {0} is{1}".format(ctry.title(),capitals[i])) break elif coutry.title() not in countries: print("{0} is not in the list. Please try again.".format (ctry)) continue f.close()The title() method is used to guarantee that if the user inputs 'japan' ( all lower case ) the elif conditions will still work.
>>> 'japan'.title() 'Japan'