Functions without explicit return
s or empty return
s will return None
.
>>> def foo():
... print("Hello")
...
>>> f = foo()
Hello
>>> f is None
True
If you don't want this, use a return
at the end of your function to return some value.
Some other tips.
Make your function only do one thing:
Currently your function is getting input, creating a list, and summing everything. This is a lot. You'll find that if you make your functions smaller, you'll get some nice benefits. You might consider something like this:
def prompt_for_number_of_inputs():
return int(input("How many elements are there in the list? ")
def prompt_for_elements(num_elements):
return [int(input("Enter a number: ")) for _ in range(num_elements)]
def sum_elements_in_list(li):
return sum(li)
so you might use it like this:
num_elements = prompt_for_number_of_inputs()
my_list = prompt_for_elements(num_elements)
print("The sum of all the elements is {0}".format(sum_elements_in_list(my_list))
Don't shadow Python built-ins:
If you call your variables the same thing as Python builtins, you'll find yourself in trouble. See here:
>>> a = list()
>>> a
[]
>>> list = [1,2,3]
>>> a = list()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Normally list()
would create an empty list (as seen above), but this is impossible because you've bound an object to the name list
. Look at other builtins which could be shadowed here.