But... def digit_sum is right there? (a.k.a.: Exercise 15.4)


#1



Hello all,

In a bit of a pickle with an error(s?) on 15.4... I get an error in the top-right pane regarding my syntax at the beginning of the "for" loop, but the Codecademy pop-up error at the bottom of the screen says it's a "global error"...and then proceeds to ask me if I have created a function called "digit_sum", which is the first line of my code. So, due to the mixed messages, I'm unsure where to start fixing this. Any thoughts would be great. :grin: Thanks!

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


def digit_sum(n):
    i=1
    total=0
    for i<=n:
        i*=10
        num=n%i
        total+=num
    return total


#2

did you see the error message in the output window? which provides more information

here:

for i<=n:

you use a for loop, but the syntax looks more like a while loop


#3

Thanks! I did see it, but I didn't know how it related to the first error message I saw below. Just tried it, and I got the gear thing, which was better than before. Will try it in Spyder and do some tests with it. :grinning:


#4

Hey! Figured it out... needed a "for" loop after all. Just needed to reverse the number that I was adjusting.

def digit_sum(n):
    total=0
    
    for i in range(n):
        num=n%10
        total+=num
        n=n/10
        
    return total

#5

personally i would use a while loop:

while n > 0:

but yes, this is very efficient code, giving working with numbers is fast, and there is no strings involved


#6

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