# Unit 8: Practice makes Perfect - Digit Sum

#1

I’ve struggled a bit with this exercise, and used the hint. I made the code following what the hint said as follows:
s = 0
t = 0
l = 0

``````def digit_sum(n):
n = str(n)
for i in n:
l = int(i)
t += l
print (t)

digit_sum(1234)
``````

The code should convert the argument into a string, then convert it into a integer on another variable, then have the variable “t” totalling it up. It returned me an error saying “local variable ‘t’ referenced before assignment”

What does this mean? And how can I fix this?

#2

`t = 0` should be inside the function so it is reset each time.

#3

oh!!!, now it works - thank you!
However I’m still confused, why does it need to reset each time? As far as I understand, I’m only executing the function once using with one argument. I’ve already set “t” to “0” at the start of the program, so why does it need to be inside the function?

I understand that “t=0” if we were to execute the function multiple times, but I don’t understand why we need it inside the function when we only execute the function only once and have already set “t” to 0.

Sorry for the dumb questions , I’m still very new to python - and I’m finding it a bit challenging compared to others.

#4

Because the function cannot return an accurate value if it (`t`) does not start at zero every time it is called.

#5

that was rather vague, but thank you regardless
I guess that’s just how python behave then, I’ll keep this in mind whenever I see a similar error occur.

#6

Vague? What is described is point on, in my view. The even larger, though ubiquitous problem is the variable in global scope.

#7

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