【问题标题】:Adding/Subtracting values in dictionary via user inputs通过用户输入在字典中添加/减去值
【发布时间】:2018-07-30 00:55:23
【问题描述】:
attributes = {"Health": 0, "Strength": 0, "Dexterity": 0,   
"Intelligence": 0}

points = 40

def add_points(attributes):
    type = input("Which attribute would you like to adjust?: ")
    if type in attributes:
        how_many = int(input("Add how many points?: "))
        if how_many <= points:
            type += how_many
    return type

add_points(attributes)

一些上下文。上面的代码是我正在构建的角色创建程序的一部分。我已经编写了整个程序,但是我想使用一个函数而不是键入一堆循环。试图让我的代码更简洁和 Pythonic。

我无法弄清楚如何获取用户选择的任何键的值并将 x 点数(也是用户选择的)添加到分配给所述键的值。

任何帮助将不胜感激!

【问题讨论】:

  • attributes[type]+= how_many.
  • P.S:只是一个旁注,避免在python中使用type关键字作为变量名。
  • madjaoue,为什么会有这样的约定?
  • 您也可以使用dict.fromkeys() 仅从名称(以及相同的 0 值)创建字典
  • 对于使用type,可能你可以在stackoverflow.com/a/10568115/5916727查看类似的讨论

标签: python function dictionary input


【解决方案1】:

取一个键的值:

 prevValue = attributes.get(type)

更改值:

attributes[type] = prevValue + how_many

【讨论】:

  • 好的,我现在已经弄清楚了那部分。当我尝试用用户选择的点数影响名为 points 的全局变量时,我对为什么 Python 会引发语法错误感到困惑。如果我使用 how_many = int(input("Add how many points?: ")) if how_many
  • 在函数声明之后的行中,添加一行 global points。然后,您只需编写points,即可在此函数中的任何位置简单地引用全局变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多