4.Digit_sum..Please help


#1

my code is:
also it is intended properly

s = 0
def digit_sum(n):
    while n != 0:
        remainder = n % 10
        s = s + remainder
        n = n / 10
    return s   
      

print digit_sum(123)

The error is :-

Traceback (most recent call last):
File "python", line 10, in
File "python", line 5, in digit_sum
UnboundLocalError: local variable 's' referenced before assignment

I am not able to move forward. Can somebody help..


#2

Assign s = 0, inside of your function.


#3

i have tried that also,but it throws an error
Oops, try again. Did you create a function called digit_sum? Your code threw a "local variable 's' referenced before assignment" erro


#4

Post the code with that included, it should work with that.


#5

Plz post full code or we cant help:grinning:


#7

Try this

def digit_sum(n):
while n != 0:
s = 0
remainder = n % 10
s = s + remainder
n = n / 10
return s

print digit_sum(123)


#8

s should be defined outside of the loop, else it gets reset to zero on every iteration.


#9

Sorry, I pasted it in the wrong place:slight_smile:


#10

That's where typing code has the advantage. We type as we think, and the code flows out naturally, especially once our fingers get trained.


#11

You type as you think. I'm a terrible typer :sweat_smile:


#12

Everybody is terrbile at some point (when starting out) but it only gets better, especially with practice. Typing is a fundamental skill. Dig around and look for a typing tutorial that teaches rest position and touch-typing where you never take your eyes off the screen. Work toward a speed of better than 30 words a minute with accuracy in the high 90 percentile. It won't come quickly but it is doable.


#13

I can type quickly and accurately with words, but it's a lot harder when the coding elements are thrown in.


#14

https://www.google.ca/search?q=typing+tutorial


#15

Again, this improves with practice. Pick a line of code and type it over and over and over and over, again. Don't stop to fix mistakes, just make less as you go. When you can comfortably type the line with no mistakes, start with another one.

    if (choice1 === "rock") {
       if (choice2 === "paper") {
       }
    }

#16

Thank you, I'm sure that will help.


#17

ありがと! Are you a moderator?


#18

Yes, but that only means we are forum caretakers. We have a broom and dustpan issued on our first day.


#19

:joy: That's amazing. My friend is trying to become a moderator.


#20

It won't happen instantly, or even quickly. On average, forum moderators here have been active contributing members for over two years. We do keep a 'watch list' of potential candidates but it can be a long time between appearing in the list and actually being approached/invited to the team. It is very important for maintaining continuity and unity as a team.


#21

I am sorry but none of your solutions work.. :sweat: