What's the deal with printing and returning values from a function?
A for-loop work as expected outside a function,
I sense it has to do with way procedure/functions operate,
Test 1: printing both numbers and sum
Test 2: printing numbers, returning sum
The natural answer tested:
By default, functions in Python evaluate to None if you don't provide a return statement in their definition.
In the statement print sum_list([1, 7, 4]), you are requesting to print the evaluation of sum_list([1, 7, 4]), which will be None in the cases where you try to print sum inside the function instead of return sum.
If you wish to use print sum inside of the function, you can do that. Instead of the statement print sum_list([1, 7, 4]), simply use sum_list([1, 7, 4]) -- don't print the evaluation of the function call. That will just run the function with the given arguments (which will run the print sum line), and not care about the evaluation of it (which by default, would be None if you don't have a return statement).
answered 03 Aug '12, 11:01
Sam the Great ♦