Digit_sum help



Traceback (most recent call last):
File "python", line 14, in
File "python", line 2, in digit_sum
NameError: global name 'n' is not defined

"Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number's digits."
I think I did some mistakes and some unefficent writing, I really appriciate the help!

def digit_sum(num):
    str(num) == n
    len(n) == l
    Number = 0
    while l > 0:
        for digits in range(l):
            Number += int(num[l]) 
            l -=1
    return Number

print digit_sum(666)


I'm guessing you meant,

n = str(num)

l = len(n)

l is a poor choice of variable since it looks so much like a 1.

Convention would have us name variables with a lowercase first letter. A capital first letter makes it look like a class name.

The for loop will be enough and we don't need to use a range since we're only looking up items, not altering them.

for digit in n:
    number += digit

As we can see, l is not needed at all.


Thank you very much!


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