当我接受num变量的用户输入时,我收到一个键错误。但是,如果我为该变量赋值,那么它的工作正常。为什么我在获取密钥的用户输入时出现关键错误?
f = open("GUTINDEX.ALL", "r", encoding="utf-8")
string = f.read()
f.close()
bookList = string.split('\n\n')
etextDict = {}
x = len(bookList)
for book in bookList:
etextDict[x] = book
x -= 1
num = input('Search by ETEXT NO:')
print(etextDict[num])
num=1
print(etextDict[num])
答案 0 :(得分:0)
这是因为用户输入是字符串(str
),而字典中的实际键是整数(int
)。首先尝试将其转换为整数:
num = int(input('Search by ETEXT NO:'))
顺便说一句,如果您只是按索引查找内容,则不需要使用字典。常规列表更容易,更快。
答案 1 :(得分:0)
输入作为字符串读取,而在用例(工作时),num是一个整数。只需将字符串转换为整数:
f = open("GUTINDEX.ALL", "r", encoding="utf-8")
string = f.read()
f.close()
bookList = string.split('\n\n')
etextDict = {}
x = len(bookList)
for book in bookList:
etextDict[x] = book
x -= 1
num = input('Search by ETEXT NO:')
print(etextDict[int(num)]) # <- changed this line
num=1
print(etextDict[num])