[Solved] Digit_sum error


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#

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

I use a loop to sum up the digit. But I don't know what's wrong with my code.


def digit_sum(n):
    while n >= 10:
        sum_number = 0
        sum_number += n % 10
        n = n/10
    else:
        sum_number += n
    return sum_number


#2

@yycenty

Well unfortunately there are a few problems, I will try to go over them the best that I can.

First off, having an else statement in the wild by itself will not allow the code to run correctly since there is no if statement before it.

Second, the reason why you are getting that error is because you never reference the variable sum_number before the return statement. The reason for this is the fact that if a number is entered that is lower than 10, the while loop will never be entered and therefore the function will try to return a variable that has not been instantiated yet resulting in the error that you see.

Lastly, Taking a look at the problem you are trying to solve, while your thinking is on the right path, the problem is really wanting you to take n and split it up into all of its digit counterparts and then add them together. For example, if n = 1234, you would want to split that number up and then add the digits together so you would end up with 1 + 2 + 3 + 4 = 10. Do you see the difference from what you are currently trying to do?

If you need more help or need me to explain anything better, let me know.


#3

Yes, this is needed.

This is largely suggestive of a mathematical solution, which is possible, but not under these conditions.

The first digit friom the right is,

x % 10

Once we have extracted that digit and accumulated it, we can truncate it...

x //= 10

#4

sum_number must be put before the sum_number, because it otherwise will not be used if n is less than 10. Then it won't be found when trying to return it as it was never executed.


#5

I was trying to explain the problem without giving too much away so that they would still try to figure it out on their own.


#6

Same here.


#7

Thank you all! I've solved the problem through two ways that suggested by the instructions.


#8

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