函数 returns 什么都没有,而不是期望值 "None"

Function returns nothing rather than the expected value "None"

我的函数中没有 return,所以我认为应该 return "None"。相反,它根本不 return 任何东西。有人能告诉我为什么吗?感谢所有帮助!

def posdivisor(n):
    for i in range(1,n+1):
        if n % i == 0:
            print(i)

someValue = eval(input("Enter an integer: "))

posdivisor(someValue)

SHELL 报告:

Enter an integer: 49
1
7
49

因为你的代码只是打印数据,函数return一个None,而你忽略它,尝试打印出来会看到None:

def posdivisor(n):
    for i in range(1,n+1):
        if n % i == 0:
            print(i)

someValue = eval(input("Enter an integer: "))

result = posdivisor(someValue)
print result

此外,这里你不需要eval(),如果你能确保输入总是数字,那么input()就可以了:

def posdivisor(n):
    for i in range(1,n+1):
        if n % i == 0:
            print(i)

someValue = input("Enter an integer: ")

result = posdivisor(someValue)
print result

python 提示将在交互评估事物时自动吞下 None

>>> def foo(): return None
>>> foo()
>>> None
>>> repr(None)
'None'