为什么我的函数返回“None”?

时间:2017-03-27 20:30:32

标签: python function

我建立了一个计算,它有效:

num = input("How many numbers would you like to add? ") 

list = []
for x in range(num):
    list.append(input('Number: '))

a = 0
for x in list:

    a=a+x
    print a

但是当我尝试对此进行功能时,根本不起作用。你能指点我吗?

list = []

def adding():
    num = input("How many numbers would you like to add? ") 

    for x in range(num):

        list.append(input('Number: '))

        a = 0
        for x in list:
            a=a+x

print adding()

3 个答案:

答案 0 :(得分:4)

没有明确return或空return的函数将返回None

>>> def foo():
...     print("Hello")
...
>>> f = foo()
Hello
>>> f is None
True

如果您不想这样做,请在函数末尾使用return返回一些值。

其他一些提示。

让你的功能只做一件事:

目前你的功能是获取输入,创建一个列表,总结一切。这很多。您会发现,如果您将功能缩小,您将获得一些不错的好处。你可能会考虑这样的事情:

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)

所以你可以像这样使用它:

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))

不要影响Python内置插件:

如果你将变量称为与Python内置变量相同的东西,那么你会发现自己陷入困境。见这里:

>>> 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

通常list()会创建一个空列表(如上所示),但这是不可能的,因为您已将对象绑定到名称list。看看其他可能被遮蔽的内置here

答案 1 :(得分:2)

你没有归还任何东西 你的缩进是不正确的 你不应该使用python builtins作为变量名(list) (注意:_通常用作一次性变量)

def adding():
    num = int(raw_input("How many numbers would you like to add? ")) 
    lst = []

    for _ in range(num):
        lst.append(int(raw_input('Number: ')))

    a = 0
    for x in lst:
        a += x
    return a

你并不需要第二个循环,因为return sum(lst)会做同样的事情 或者,您根本不需要lst

def adding():
    num = int(raw_input("How many numbers would you like to add? ")) 

    a = 0
    for _ in range(num):
        x = int(raw_input('Number: '))
        a += x
    return a

答案 2 :(得分:0)

我更改了列表的变量名称,因为它隐藏了内置名称并添加了return语句。按照你的意图工作。

sumlist = []

def adding():
    num = input("How many numbers would you like to add? ") 

    for x in range(int(num)):

        sumlist.append(int(input('Number: ')))

        a = 0
        for x in sumlist:
            a=a+x

    return a

print(adding())