Python Prime数字循环

时间:2014-11-12 01:58:03

标签: python while-loop primes function

运行此代码时,我一直有错误。我想知道出了什么问题。代码必须能够读取单词和整数并重复提示(请输入一个整数> = 2:'),直到它大于或等于2.提前感谢。

def prime_number():

    prime_num = input('Please enter an integer >= 2: ')

    while not(prime_num.isdigit() and int(prime_num)<1):

        prime_num = input('Please enter an integer >= 2: ')

    for i in range(2,int(prime_num)+1):
        for x in range(2,i):
            if i%x == 0:
                break
        else:
            print (i)

2 个答案:

答案 0 :(得分:0)

  1. 如@rpattiso所述,您没有调用方法和
  2. while条件是错误的
  3. 这应该有效:

    def prime_number():
        prime_num = input('Please enter an integer >= 2: ')
    
        while not (prime_num.isdigit() and not int(prime_num)<1):
            prime_num = input('Please enter an integer >= 2: ')
    
        for i in range(2,int(prime_num)+1):
            for x in range(2,i):
                if i%x == 0:
                    break
            else:
                print (i)
    prime_number()
    

答案 1 :(得分:0)

您需要输入该功能。这通常在python中完成:

def prime_number():
    prime_num = input('Please enter an integer >= 2: ')    
    while not(prime_num.isdigit() and int(prime_num)<1):    
        prime_num = input('Please enter an integer >= 2: ')

    for i in range(2,int(prime_num)+1):
        for x in range(2,i):
            if i%x == 0:
                break
        else:
            print (i)


if __name__ == "__main__":
    prime_number()        

一般的一些建议。我将输入逻辑与素数计算逻辑分开。