我试图将参数a和b传递给本地函数" isPrimes"用作范围

时间:2017-09-28 15:29:49

标签: python-3.x

如果我尝试在其上运行isPrime函数 - 用任何整数替换n,它会发现它是否是素数;但是从a获取bprimes作为数字范围以检查它们是否为素数是问题所在。

def primes(a,b):
    pass

def isPrime(n):
    # I want to make n take the values of a and b so that the is Prime
    # function executes all the prime numbers within the range a to b
    if n == 1:
        return False
    # here I've tried referencing n and (a,b) as the range but neither
    # option does anything
    for z in range(a, b):
        if n % z == 0:
            return False
    else:
        # this is supposed to print the n each time it comes up as a prime
        # number but when I run this nothing happens and I'm not sure where
        # I'm going wrong
        print(n)
        return True

1 个答案:

答案 0 :(得分:0)

  1. 切换return和print语句的顺序。你的计划是 在执行print语句之前结束
  2. 如果要指定要测试的范围,如果a 数字是素数,你要么必须在你的中声明a和b 函数,或作为参数传递。
  3. 在您的范围语句中,对于从a到b的每个整数,但只要n%z = 0,就会返回false。当您尝试在带素数的素数上使用%运算符时会发生这种情况(例如17) %17将返回false)。添加一个语句来比较n!= z。
  4. 在if语句中返回false,在else语句中返回true。这意味着您的代码只会在函数退出之前进行一次比较。在程序结束时添加return true语句。
  5. 见下文:

    def isPrime(n):
        a = 2
        b = 100000
    
        if n == 1:
            print("1 is not a prime number.")
            return False
    
        for z in range(a,b):  
            if n%z==0 and n != z:
                print(str(n) + " is not a prime number.")
                return False
    
        print(str(n) + " is a prime number.")
        return True