下面代码的目的是让用户从输出的列表中输入一个与老板对应的数字(字符串(,然后输出老板的全名。例如,如果我输入4,我希望输出为4。双胞胎愤怒。如果我使用print(d[4](,那么输出就是我所期望的,但是当我使用print时(d[boss_input](,我会得到错误:
追踪(最近一次通话(:文件";c: \Users\Alex \Desktop\Python Code\Runescape Boss Drop Calculator.py",第24行,inprint(d[boss_input](KeyError:"4">
代码:
import random
print("RuneScape drop log calculator")
d = {1: "1. Vindicta and Gorvek", 2: "2. Gregorovic", 3: "3. Helwyr", 4: "4. Twin Furies"} # create a library that will map the numeric value to the boss name
boss_name = [
"1. Vindicta and Gorvek",
"2. Gregorovic",
"3. Helwyr",
"4. Twin Furies"
]
print(boss_name)
boss_input = input("Please enter the number corresponding to the boss you would like to calulcate the drop rates for: ")
boss_name.index("2. Gregorovic")
print(d[boss_input])
有人能告诉我我做错了什么吗?我对此很陌生,所以很可能有一个简单的解决方案。谢谢
您需要将输入强制转换为int
。
替换:
boss_input = input("Please enter the number corresponding to the boss you would like to calulcate the drop rates for: ")
发件人:
boss_input = int(input("Please enter the number corresponding to the boss you would like to calulcate the drop rates for: "))
print(d[boss_input])
4. Twin Furies
替换,字典由@TimRoberts 建议
boss_name = {
"1": "1. Vindicta and Gorvek",
"2": "2. Gregorovic",
"3": "3. Helwyr",
"4": "4. Twin Furies"
}
boss_input = input("Please enter the number corresponding to the boss you would like to calulcate the drop rates for: ")
print(boss_name.get(boss_input, f"Please select a number between [1-{len(boss_name)}]"))
函数input()
返回字符串,作为需要integer的关键字(在该代码中(,因此通过将其强制转换为integer
print(d[int(boss_input)])
Corralien或Samor答案将起作用。如果你只是在学习,你可以删除大部分代码并使用它。
print("RuneScape drop log calculator")
d = {1: "1. Vindicta and Gorvek", 2: "2. Gregorovic", 3: "3. Helwyr", 4: "4. Twin Furies"} # create a library that will map the numeric value to the boss name
boss_input = int(input("Please enter the number corresponding to the boss you would like to calulcate the drop rates for: "))
print(d[boss_input])