What is wrong here? from basics explain


#1



Oops, try again. Did you create a function called digit_sum? Your code threw a "local variable 'sum' referenced before assignment" error.

It should return the sum of digits ,i guess .

def digit_sum(n):
   while n>0:
       for digits in range(len(str(n))):
           sum+=int(str(n)[digits])
   return sum


#2

Sometimes, python has this issue, try...

sum = sum+int(str(n)[digits])


#3

i think the problem is that they're using sum
try replacing sum with a variable like total or result because sum is a reserved word in python


#4

Indeed @kyleaw is correct! I forgot that sum is indeed a reserved word. That'd be your issue. Thanks for the reminder! :smiley:


#5

no problemo, friend :slight_smile:


#6

I used this code:

def digit_sum(n):
   while n>0:
       for digits in range(len(str(n))):
           
           total=total+int(str(n)[digits])
   return total

it still shows this error:"Oops, try again. Did you create a function called digit_sum? Your code threw a "local variable 'total' referenced before assignment" error. "


#7

here is a problem:

total=total # rest of the code

you add something tot total, while total is undefined? Maybe you should define total somewhere (at the right place) and set it to zero?


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.