While dealing with Dictionary elements in Python faced unsupported operand type(s) for +=: 'int' and 'NoneType'

128 Views Asked by At

The problem is that while running this code everything is fine:

d={'9h':9, 'Qd':10}
l=['9h', 'Qd', 'test', 'test2']
s=0
for i in range(len(l)):
    if l[i] in d:
        s += d.get(l[i])
print s

But while doing it with classes I got the error "unsupported operand type(s) for +=: 'int' and 'NoneType'"

Here is my class implementation:

def __init__(self, plr_cur_value, plr_result_score):
        self.plr_cur_value = plr_cur_value
        self.plr_result_score = plr_result_score

def deck_adjust(self):        
    for i in range(len(self.plr_cur_value)):
        if self.plr_cur_value[i] in self.d:
            self.plr_result_score + = self.d.get(plr_cur_value[i])

    return self.plr_result_score
1

There are 1 best solutions below

0
quamrana On

It sounds like you might have formatting errors where the score += value line is always being executed and value might be `None.

Another possibility is that your dictionary contains the indicated key, but the corresponding value is None.

The following code might solve several problems in one:

d = {'9h':9, 'Qd':10}
l = ['9h', 'Qd', 'test', 'test2']
s = 0
for i in l:
    s += d.get(i, 0)
print(s)

Output:

19