【问题标题】:Function returns nothing rather than the expected value "None"函数只返回预期值“None”而不返回任何内容
【发布时间】:2023-03-27 13:12:01
【问题描述】:

我的函数没有返回值,所以我认为它应该返回“无”。相反,它根本不返回任何东西。有人能告诉我为什么吗?感谢所有帮助!

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

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

posdivisor(someValue)

壳牌报告:

Enter an integer: 49
1
7
49

【问题讨论】:

  • 您在控制台中看到的打印内容。
  • 您是在交互式外壳中执行此操作吗?如果返回None,则shell 不会显示任何内容。如果您使用posdivisor(someValue),您应该会看到“None”打印出来。
  • 这样使用eval邪恶的。请改用int
  • 我正在做一个文件中的代码,然后打印到外壳。我认为 shell 会打印“None”,因为如果我将代码中的最后一行更改为“print(posdivisor(someValue))”,那么 shell 会打印“None”。

标签: python function return


【解决方案1】:

因为你的代码只是打印数据,函数返回一个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

【讨论】:

    【解决方案2】:

    在交互式评估事物时,python 提示符会自动吞下None

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

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      相关资源
      最近更新 更多