0

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
quamrana
  • 37,849
  • 12
  • 53
  • 71
Roft
  • 3
  • 5
  • The error comes up while dealing with the method deck_adjust(self) at the line "self.plr_result_score + = self.d.get(plr_cur_value[i]) – Roft Jan 08 '18 at 15:03
  • I notice that you're missing a `self` before the `plr_cur_value[i]` in that line. Could that be it? – nnnmmm Jan 08 '18 at 15:16
  • The order the error gives is important. lhs is `int`, rhs is `NoneType`, meaning whatever you're trying to add in (`self.d.get(plr_cur_value[i])` is returning `None`. Whatever you're trying to find in the dictionary `d` doesn't exist, hence `.get` is returning `None` as the default (if you'd accessed this with square brackets, it would throw an exception instead). –  Jan 08 '18 at 15:20
  • @nnnnmmm, THaank you so much. You are right, I missed the self. :) stupid me. Yes, the d.get () is to return integers that are values of keys in a dictionary. – Roft Jan 08 '18 at 15:24
  • 2
    Also note that `for i in range(len(stuff))` is as anti-idiomatic as it gets in Python. The language has a "for each" construct to iterate over elements of a sequence naturally, no need to use double indirections through the indices of a sequence. `for value in self.plr_cur_value:` is all you need. – jsbueno Jan 08 '18 at 15:27
  • for value in self.plr_cur_value: didn't work for me. That is why I went for range() construction. – Roft Jan 08 '18 at 20:10

1 Answers1

0

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
quamrana
  • 37,849
  • 12
  • 53
  • 71