简体   繁体   English

Python function 返回语句后继续运行?

[英]Python function continues running after return statement?

The following function ends with the TypeError: Unsupported operand types float and NoneType.以下 function 以 TypeError 结尾:Unsupported operand types float and NoneType。 How is it possible for a base case to fire a return None and the program continue with factorial() = None .基本案例如何触发return None并且程序继续使用factorial() = None At least this is how I perceive it.至少我是这样认为的。

def factorial(i):
  if i < 0:
    return None # Why does the program not stop here?...
  if i == 0:
    return 1
  return i * factorial(i-1) #factorial(i-1) returns None after i < 0?

print(factorial(3.01))

You're getting that error because return i * factorial(i-1) is getting called in your function, and factorial(i-1) is evaluating to None .您收到该错误是因为在您的 function 中调用了return i * factorial(i-1) ,而factorial(i-1)的计算结果为None

The reason it's evaluating to None is the input value you gave - 3.01 - this will result in the following:它评估为None的原因是您提供的输入值 - 3.01 - 这将导致以下结果:

factorial(3.01) # returns 3.01 * factorial(3.01-1)
factorial(2.01) # returns 2.01 * factorial(2.01-1)
factorial(1.01) # returns 1.01 * factorial(1.01-1)
factorial(0.01) # returns 0.01 * factorial(0.01-1)
factorial(-0.99) # returns None (because i < 0)

Therefore, the line 0.01 * None is run, which results in your error.因此,运行0.01 * None行,这会导致您的错误。

The last recursive call in your function is function 中的最后一次递归调用是

return 0.01 * factorial(-0.99)

factorial(-0.99) invokes the if i < 0: case, so it returns None . factorial(-0.99)调用if i < 0:案例,因此它返回None Then the above code tries to multiply 0.01 * None , which causes the error you got.然后上面的代码试图乘以0.01 * None ,这会导致你得到的错误。

Your definition of factorial is only valid for non-negative integers.您对factorial的定义仅对非负整数有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM