【问题标题】:Python: Why variable is treated as a 'NoneType' despite having been defined as an integer?Python:尽管变量被定义为整数,为什么变量被视为“NoneType”?
【发布时间】:2020-07-01 08:52:55
【问题描述】:

我正在用 Python 编写一个简单的脚本作为评估 Ackermann Function 的练习。首先脚本要求用户输入,然后尝试计算其余部分。代码如下:

m = int(input('Please input m.\n'))
n = int(input('Please input n.\n'))


def compute(m, n):
    if m == 0:
        print(n + 1)
    elif m > 0 and n == 0:
        compute(m - 1, 1)
    else:
        compute(m - 1, compute(m, n - 1))


compute(m, n)

让我感到困惑的部分是它返回 TypeError 时,特别是对于 compute(m, n) 中我尝试从 n 和 m 加或减 1 的行。

print(n + 1)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

我知道 Python 将所有输入都作为字符串,这就是我专门转换输入的原因 在脚本的最开始使用 int() 。然而,TypeError 似乎暗示在 compute(m, n) 中,m 和 n 不是 int,而是 NoneType,因此它们不能相加或相减。为什么会这样,我该如何解决?

【问题讨论】:

  • compute 是递归的,但没有显式返回,这意味着始终返回 None
  • 您的函数没有返回结果。如果m 为零,它所做的就是打印n+1。递归调用都不起作用。
  • Python 默认返回 None 。递归必须至少有一个停止条件。否则会导致stackoverlow。
  • 感谢cmets,我现在明白了。
  • 这能回答你的问题吗? Why does my recursive function return None?

标签: python recursion return typeerror


【解决方案1】:

任何fruitful 递归函数都必须有一个或多个return 语句。请参阅this

m = int(input('Please input m.\n'))
n = int(input('Please input n.\n'))

def compute(m, n):
    if m == 0:
        return n + 1
    elif m > 0 and n == 0:
        return compute(m - 1, 1)
    else:
        return compute(m - 1, compute(m, n - 1))


print(compute(m, n))

应该如你所愿。

【讨论】:

  • 最好解释一下您实际更改了什么以及为什么它可以解决问题,而不是仅仅放一段代码
猜你喜欢
  • 2019-03-05
  • 2017-06-01
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 2020-01-08
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多