我已将此代码放入更大的代码块中,但我已将其缩小为此错误。我知道错误是我试图在字典中添加变量。有什么方法可以将它添加到实际的统计数据中吗?
smallGuns = 5
bigGuns = 2
unarmed = 3
meleeWeapons = 20
throwing = 4
firstAid = 2
sneak = 5
lockpick = 10
steal = 3
science = 4
repair = 3
speech = 5
choice = raw_input("Which stat do you want to add points to?")
skillPoints = 5
statlist = ['small guns', 'big guns', 'unarmed', 'melee weapons', 'throwing', 'first aid' 'sneak', 'lockpick', 'steal', 'science', 'repair', 'speech']
if choice in statlist:
pointDeduction = input("How many points do you wish to add to %s? (Up to %s points)" %(choice, skillPoints))
if pointDeduction <= choice:
choice += pointDeduction
skillPoints -= pointDeduction
else:
print "You do not have that many points to distribute to %s." %(choice)
print steal
我的错误讯息是
Traceback (most recent call last): File "F:/TARG/temp.py", line 22, in <module> choice += pointDeduction TypeError: cannot concatenate 'str' and 'int' objects
答案 0 :(得分:0)
您的示例目前没有词典。你错误地启动了它。它应该如下:
statlist = {"attribute_name" : attribute_value, REPEAT}
一旦你有正确的词典初始化
statlist = {'small guns' : 5, 'big guns' : 2, 'unarmed' : 3} # you do the rest
choice = raw_input("Which stat do you want to add points to?")
if choice in statlist:
pointDeduction = input("How many points do you wish to add to %s? (Up to %s points)" %(choice, skillPoints))
if pointDeduction <= statlist[choice]:
statlist[choice] -= pointDeduction
skillPoints -= pointDeduction
else:
print "You do not have that many points to distribute to %s." %(choice)
分发积分时也存在一些逻辑问题,但您可以自行解决这个问题。
答案 1 :(得分:0)
我猜测你的代码statlist
是一个stat
密钥的字典stat value
。现在你有一个列表,所以基本上你说“如果项目在列表中,将数字连接到它的末尾”(虽然不正确)。
您要做的是在问题中添加词典。你声明变量的第一部分并不是必需的,你可以像这样完成它:
statlist = {'small guns' : 5, 'big guns' : 2, ...}
对于每个值。然后,改变统计数据:
if choice in statlist:
pointDeduction = input("How many points do you wish to add to %s? (Up to %s points)" %(choice, skillPoints))
if pointDeduction <= statlist[choice]:
statlist[choice] += pointDeduction
skillPoints -= pointDeduction
else:
print "You do not have that many points to distribute to %s." %(choice)
答案 2 :(得分:0)
在dict中收集你的统计数据并使用它。
choice = raw_input("Which stat do you want to add points to?")
skillPoints = 5
statlist = {'small guns': 5, 'big guns': 2, 'unarmed': 3, 'melee weapons': 20, 'throwing':4, 'first aid':2, 'sneak': 5, 'lockpick': 10, 'steal': 3, 'science': 4, 'repair': 3, 'speech': 5}
if choice in statlist:
pointDeduction = int(raw_input("How many points do you wish to add to %s? (Up to %d points)" %(statlist[choice], skillPoints)))
if pointDeduction <= skillPoints:
statlist[choice] += pointDeduction
skillPoints -= pointDeduction
else:
print "You do not have that many points to distribute to %s." %(choice)
print statlist[choice]
else:
print 'you entered an invalid choice'
要打印值,您可以执行以下操作
# print an individual entry
print 'My small guns points are %d' % statlist['small guns']
# print all entries in a loop
print 'My points inventory is'
for key, value in statlist.iteritems():
print '%s = %d' % (key, value)