下面的代码是我的课程中使用的代码。此时,"if int(what_skill) <0 or int(what_skill) > 9:“行产生了上面的错误。我尝试将其更改为str(),但是这又产生了另一个错误。
def player():
vigor = 1
endurance = 1
strength = 1
dexterity = 1
intelligence = 1
luck = 1
points = 25
while points !=0:
what_skill = input("What skill would you like to add to? Vigor, Endurance, Strength, Dexterity, Intelligance, Luck? ")
print(what_skill)
add_points = int(input("You have " + str(points) + " points left. How many points from 1-9 would you like to add to " + str(what_skill) + "? "))
if int(add_points) > 9:
print("Too many points")
print(add_points)
else:
if int(what_skill) < 0 or int(what_skill) > 9:
print("invaid choice")
else:
update_skill = int(what_skill) + int(add_points)
points = points - add_points发布于 2020-02-05 18:35:43
您看到错误的原因是因为这些行
int(what_skill)在您的示例中,这等同于
int("luck")这没有任何意义-我认为您正在尝试使用int(luck) --引用变量中的数字
我会把你的技能改成字典,并使用下面这样的东西:
stats = {
"Luck": 1,
"Vigor": 1,
"Endurance": 1,
"Strength": 1,
"Dexterity": 1,
"Intelligence" : 1
}
points = 25
while points >= 1:
what_skill = input("What skill would you like to add to? Vigor, Endurance, Strength, Dexterity, Intelligance, Luck? ")
add_points = int(input("You have " + str(points) + " points left. How many points from 1-9 would you like to add to " + str(what_skill) + "? "))
if int(add_points) > 9:
print("Too many points")
else:
if stats[what_skill] < 0 or stats[what_skill] > 9:
print("invalid choice")
else:
update_skill = stats[what_skill] + int(add_points)
points = points - add_points发布于 2020-02-05 18:53:59
您会收到此错误,因为what_skill是字符串类型,并且通过类型转换,您无法将单词转换为整数。int('abc')将导致与您面临的错误相同的错误。
如果你想引用你在一开始初始化的变量,使用字典代替,key是技能,值是各自的点。现在,您可以作为myDict[what_skill]访问这些点。到目前为止,使用字典是最有效的解决方案。
https://stackoverflow.com/questions/60073734
复制相似问题