【问题标题】:How fix the error :invalid literal for int() with base 10: 'Luck'?如何修复错误:int() 以 10 为底的无效文字:'Luck'?
【发布时间】:2020-05-21 05:54:11
【问题描述】:

下面的代码是我的课程中使用的。目前,“if int(what_skill) 9:”行正在产生上述错误。我尝试将其更改为 str() 但这会产生另一个错误。

定义播放器():

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

【问题讨论】:

  • "Luck" 是一个字符串——你试图将它转换为一个 int 是没有意义的
  • what_skill是技能name,你的积分是add_points,所以int(what_skill)显然会破码。

标签: python python-3.x loops variables exception


【解决方案1】:

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

如果您想引用一开始就初始化的变量,请改用字典,其中键是技能,值是相应的点。现在,您可以通过myDict[what_skill] 访问这些积分。使用字典是迄今为止最有效的解决方案。

【讨论】:

    【解决方案2】:

    您看到错误的原因是因为线条

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 2023-04-03
      • 2021-01-28
      • 2012-05-14
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      相关资源
      最近更新 更多