Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过用户输入在字典中添加/减去值 attributes={“健康”:0,“力量”:0,“灵巧”:0, “智能”:0} 分数=40 def添加_点(属性): type=input(“要调整哪个属性?”:) 如果键入属性: how_many=int(输入(“添加多少点:”) 如果取一个键的值的次数_Python_Function_Dictionary_Input - Fatal编程技术网

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