python - 类型错误:* 不支持的操作数类型: 'NoneType' 和 'int'

标签 python python-3.x recursion typeerror nonetype

我找不到下面这段代码中的错误。如果我在 else 部分说“return”而不是“print”,代码就不能执行 else 部分,它只会在 if 部分进行计算。我怎样才能解决这个问题?

def calculatePerimeter(length, depth):
    if depth == 1:
        return 3 * length
    else:
        print (calculatePerimeter(length, depth-1) * (4/3)**(depth)) / ((4/3)**(depth-1))

calculatePerimeter(100, 3)

最佳答案

您需要在 else 子句中返回值,否则没有什么可以相乘(除了在递归中进行最后一次调用时)。那么在调用函数的时候需要调用print

def calculatePerimeter(length, depth):
    if depth == 1:
        return 3 * length
    else:
        return (calculatePerimeter(length, depth-1) * (4/3)**(depth)) / ((4/3)**(depth-1))

print(calculatePerimeter(100, 3))

关于python - 类型错误:* 不支持的操作数类型: 'NoneType' 和 'int',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36961007/

相关文章:

c++ - "invalid initialization of non-const reference of type ‘int&’ 来自类型为 ‘int’ 的右值 ": Recursive pass-by-reference function

javascript - js递归函数未返回正确的子对象

python - 如何获取绑定(bind)方法的定义类?

python - python 3.3 的 urllib.request 无法下载文件

java - 显示注册某个字符串的所有可能组合的递归方法

java - 卡住/编译和管道 java python 应用程序?

python - 机器人回原点

python - 如何使用文本文件中的单选按钮

python - 在 ASP 中 - 为什么我可以从 vbscript 调用 python 函数,但反之则不行?

python - 过滤满足一组条件的多对多关系