Hi, I have a question about this exercise: which is de difference between printing the value and returning it? I mean, if my code is like this: def digit_sum(n): suma=0 for i in str(n): suma=suma+int(i) return suma it works perfectly. But if instead of return I use print, it displays the following error: Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11: def digit_sum(n): suma=0 for i in str(n): suma=suma+int(i) print suma Why is that? Why does print return null? And if I use return and then call the function, it still doesn't display anything: def digit_sum(n): suma=0 for i in str(n): suma=suma+int(i) return suma digit_sum(123456) Why? Regards
You have this, which does call the function ...
However, when you use
return within the function, do this when you call it to display the result ...
Thanks for your reply, it does work now!
But I'm still not understanding why print inside the function is not working properly.
Does it display the result when you call the function? It might do that, however, Codecademy wants the function to actually
return the result, which makes it available outside the function, not only for displaying it, but also to enable the result to be used for further processing, such as using it in an expression.
If a function displays a result, but does not
return it, you can see the result, but without a
return, it is not made available for potential further use by the program.
That makes sense! Now it's returning and also printing the value.
Thanks a lot!
2 posts were split to a new topic: Sum of digits of 0303 is 15 - Why?
Sum of digits of 0303 is 15 - Why?