返回语句的 Python 问题 [英] Python issues with return statement

查看:63
本文介绍了返回语句的 Python 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我对 python 很陌生,想知道您是否可以帮我做点什么.我一直在玩这个代码,但似乎无法让它工作.

 导入数学定义主():如果 isPrime(2,7):打印(是")别的:打印(否")def isPrime(i,n):如果 ((n % i == 0) 和 (i <= math.sqrt(n))):返回错误如果 (i >= math.sqrt(n)):打印(是质数:",n)返回真别的:isPrime(i+1,n)主要的()

现在 isPrime 方法的输出如下:

是质数:7不

我确定该函数应该返回 true,然后它应该打印Yes".我错过了什么吗?

解决方案

您正在丢弃递归调用的返回值:

def isPrime(i,n):如果 ((n % i == 0) 和 (i <= math.sqrt(n))):返回错误如果 (i >= math.sqrt(n)):打印(是质数:",n)返回真别的:#这里不返回isPrime(i+1,n)

您也想传播递归调用的值,包括一个 return 语句:

其他:返回 isPrime(i+1,n)

现在您的代码打印:

<预><代码>>>>isPrime(2,7)是素数:7真的

Hello I'm very new to python and was wondering if you could help me with something. I've been playing around with this code and can't seem to get it to work.

    import math

def main():
    if isPrime(2,7):
        print("Yes")
    else:
        print("No")

def isPrime(i,n):
    if ((n % i == 0) and (i <= math.sqrt(n))):
        return False
    if (i >= math.sqrt(n)):
        print ("is Prime: ",n)
        return True
    else:
        isPrime(i+1,n)
main()

Now the output for the isPrime method is as follows:

is Prime:  7
No

I'm sure the function should return true then it should print "Yes". Am I missing something?

解决方案

You are discarding the return value for the recursive call:

def isPrime(i,n):
    if ((n % i == 0) and (i <= math.sqrt(n))):
        return False
    if (i >= math.sqrt(n)):
        print ("is Prime: ",n)
        return True
    else:
        # No return here
        isPrime(i+1,n)

You want to propagate the value of the recursive call too, include a return statement:

else:
    return isPrime(i+1,n)

Now your code prints:

>>> isPrime(2,7)
is Prime:  7
True

这篇关于返回语句的 Python 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆