Python 通过用户输入在字典中添加/减去值 attributes={“健康”:0,“力量”:0,“灵巧”:0, “智能”:0} 分数=40 def添加_点(属性): type=input(“要调整哪个属性?”:) 如果键入属性: how_many=int(输入(“添加多少点:”) 如果取一个键的值的次数
:Python 通过用户输入在字典中添加/减去值 attributes={“健康”:0,“力量”:0,“灵巧”:0, “智能”:0} 分数=40 def添加_点(属性): type=input(“要调整哪个属性?”:) 如果键入属性: how_many=int(输入(“添加多少点:”) 如果取一个键的值的次数,python,function,dictionary,input,Python,Function,Dictionary,Input,: 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 h
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)
要更改该值,请执行以下操作:
prevValue = attributes.get(type)
attributes[type]+=how_numbers
.P.S:只是一句旁注,避免在python中使用type
关键字作为变量名。madjaoue,为什么这是一种约定?您还可以使用dict.fromkeys()
仅从名称(和相同的0值)创建字典,以便使用type
,也许你们可以在《Ok》中进行类似的讨论,我现在已经弄明白了这一部分。当我试图用用户选择的点数来影响名为points的全局变量时,我对Python为什么抛出语法错误感到困惑。如果我使用how_many=int(输入(“添加多少个点:”),如果函数声明后的行上有how_many,则添加一行,显示全局点
。然后,只需写入点
,即可在该函数中的任何位置引用全局变量。
attributes[type] = prevValue + how_many