Why Doesn't This Code Work?


#1




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:
    alist.append(i)
  for x in alist:
    total += int(x)
  print total


#2

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


#3

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?


#4

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


#5

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


#6

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


#7

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


#8

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