【发布时间】:2020-07-01 17:58:10
【问题描述】:
大家好,所以我有这个包含国家和首都列表的记事本。 然后我想输入国家名称以显示首都,所以这就是我感到困惑的地方。
country.txt
malaysia, vietnam, myanmar, china, sri lanka, japan, brazil, usa, australia, thailand, russia, uk
kuala lumpur, hanoi, yangon, beijing, colombo, tokyo, rio, washington, canberra, bangkok, moscow, london
这是国家和首都的记事本文件
f = open(r'C:\Users\User\Desktop\country.txt')
count = 0
for line in f:
line = line.rstrip('\n')
rec = line.split(',')
count = count + 1
ctry = input('\nEnter country name: ')
ctry = ctry.lower()
for i in country:
if ctry == country[i]:
print ('country:', ctry)
print ('capital:', capital[i])
break
else:
print ('country not in the list')
这是我不知道该怎么做才能让它工作的地方。
我希望输出是这样的
Enter country name: vietnam
Country: vietnam
Capital: hanoi
当列表中没有国家时
Enter country name: france
Country not in the list
【问题讨论】:
-
你的
country变量中有什么?你遇到了什么错误? -
和
capital[i]一样,这里没有定义capital -
Traceback (most recent call last): File "C:\Users\User\Desktop\Q3.py", line 13, in <module> for i in country: NameError: name 'country' is not defined
标签: python list for-loop input notepad