简体   繁体   English

当我有返回值时,Python 不返回任何值

[英]Python returns none when I do have a return value

I'm making a refresher on recursion and i've made a python file like this:我正在复习递归,我制作了一个这样的 python 文件:

#!/usr/bin/python
import sys

if (len(sys.argv)!=3):
    raise ValueError('Please provide two dimensions.')
else:
    pass

def plotLand(a,b):
    if(a==b):
        print(a)
        return a
    if(a<b):
        c=b%a
        b = c if(c!=0) else a
    else:
        c = a%b
        a = c if (c!=0) else b
    plotLand(a,b)
result = plotLand(int(sys.argv[1]),int(sys.argv[2]))
print(result)

I added the print(a) just to check if my function was returning a value.我添加了print(a)只是为了检查我的函数是否正在返回一个值。 I call this file in linux terminal in this way:我以这种方式在 linux 终端中调用此文件:

python algorithms.py 1680 64

And this is my output:这是我的输出:

80
None

The print function inside my recursive function is printing the value, but I'm not getting the return value of the function.我的递归函数中的打印函数正在打印值,但我没有得到函数的返回值。 The original function didn't have the print function, as I mentioned before.正如我之前提到的,原始功能没有打印功能。

Recursive functions work exactly like non-recursive functions – if you don't write return and a value, you're returning None , and you only return anything when a == b .递归函数的工作方式与非递归函数完全一样——如果你不写return和一个值,你将返回None ,并且只有当a == b时才返回任何内容。

You need你需要

return plotLand(a,b)

I also think that you could shorten your code to我还认为您可以将代码缩短为

def plotLand(a,b):
    small, large = sorted((a,b))
    remainder = large % small
    return plotLand(remainder, small) if remainder else a 

You only return for one condition.你只返回一个条件。 You can consider adding a default at the end of the function可以考虑在函数末尾添加一个默认值

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

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