首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复错误:基数为10的int()的文本无效:'Luck'?

如何修复错误:基数为10的int()的文本无效:'Luck'?
EN

Stack Overflow用户
提问于 2020-02-05 18:28:17
回答 2查看 35关注 0票数 1

下面的代码是我的课程中使用的代码。此时,"if int(what_skill) <0 or int(what_skill) > 9:“行产生了上面的错误。我尝试将其更改为str(),但是这又产生了另一个错误。

def player():

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-05 18:35:43

您看到错误的原因是因为这些行

代码语言:javascript
复制
int(what_skill)

在您的示例中,这等同于

代码语言:javascript
复制
int("luck")

这没有任何意义-我认为您正在尝试使用int(luck) --引用变量中的数字

我会把你的技能改成字典,并使用下面这样的东西:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2020-02-05 18:53:59

您会收到此错误,因为what_skill是字符串类型,并且通过类型转换,您无法将单词转换为整数。int('abc')将导致与您面临的错误相同的错误。

如果你想引用你在一开始初始化的变量,使用字典代替,key是技能,值是各自的点。现在,您可以作为myDict[what_skill]访问这些点。到目前为止,使用字典是最有效的解决方案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60073734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档