Why Doesn't This Code Work?


When I run the following code in repl.it, it functions correctly. However, when I run it in the codecademy assignment, I receive the following error: "Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11."

Why is this?

def digit_sum(n):
  numbers = str(n)
  alist = []
  total = 0
  for i in numbers:
  for x in alist:
    total += int(x)
  print total


if you need to return, use the return keyword, currently you are only printing

also, why two loops? you can loop over numbers and add i to total directly


Got it - changing to "return total" fixed the issue.

Can you show me an example of how to run the code with only one loop?


well simply, here you loop over numbers:

for i in numbers:

and instead of appending them to a list, you can add them to total directly:

total += int(i)

i don't see why you should first append to list, and then to total if you can do this in one step


You have to remember that strings are able to be iterated through just like lists.


Ah, I definitely did not know/remember that - thanks!


uhm... i am confused, you looped through a string here:

for i in numbers:

how can you then not remember you can over a string? Code is conflicting with information i get


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