(May-20-2018, 06:27 AM)wavic Wrote:data = f.readlines() countries = [] # this is the storage list for the countries. An empty list capitals = [] # this one is for the capitals for line in data: line = line.rstrip('\n') country, capital = line.split(',') countries.append(country) # append 'country' to 'countries'. capitals.append(capital) # append 'capital' to 'capitals'Now in the second part of the script, you can't use '==' operator to check if an object is in the list. Line 23. They are different types. One is a string and another list of strings. The way you do it is to use 'in'. Almost plain English.elif line in countries:
It stored. But it doesn't come out the output as I thought.
It only pops "The capital of Russia is Moscow" whenever I typed any other countries.
This is the code:
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') country, 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:1}\t{1:26}\t {2:24}".format(count,country,capital)) while True: line = str(input("Enter a country name (x to Exit): ")) if line == 'x': break elif line in countries: print ("The capital of {0} is{1}".format(country,capital)) else: print("The country is not in the list. Please try again.") f.close()
Output:Enter a country name (x to Exit): Malaysia
The capital of Russia is Moscow