我可以让for循环运行整个范围吗?

时间:2018-10-12 16:53:22

标签: python loops

这是我的代码。我正在尝试查找等于或等于输入整数的质数。但是,似乎循环会在看到符合要求的范围内的整数时停止。不幸的是,这不是我想要的。在做出判断之前,我想使其通过范围内的所有测试。这可能吗?如果是这样,我该怎么做?谢谢。

def getNumber(main):
    n = int(input())
return n


def isPrime(n):
    list=[2]
    if n > 1:
        for i in range(2, n+1):
            for a in range (2, n):
                if i*a != i and i%a != 0 and i%2 != 0:
                    list.append(i)
                    break
        return "\n".join(map(str, list))`

def main():
n = getNumber(main)
print(isPrime(n))

main()

2 个答案:

答案 0 :(得分:1)

您的逻辑有些错误。这是您的代码正在做的事情:

  1. 2到输入的n,以递增的顺序检查数字。
  2. 对于每个数字i,检查a2之间是否有任何数字n除以i
  3. 如果ai,则将i添加到列表中,然后移至下一个i

这不会给你一个质数。实际上,我很难弄清楚它会给您什么,但质数可能不是。改为查看此函数,它将返回所有小于或等于给定数字的质数-您可以将其与代码进行比较,以弄清哪里出了错:

def getPrimesLessThanOrEqualTo(n):
    if n <= 1:                # Anything 1 or less has no primes less than it.
        return ""             #    So, return nothing.
    list = [2]                # 2 is the lowest prime number <= n
    for i in range(3, n+1):   # We start at 3 because there's no need to re-check 2
        for a in list:        # Instead of iterating through everything less than
                              #   i, we can just see if i is divisible by any of 
                              #   the primes we've already found
            if i % a == 0:    # If one of the primes we've found divides i evenly...
                break         # then go ahead and try the next i
            list.append(i)    # Now, if we got through that last bit without 
                              #   hitting the break statement, we add i to our list
    return "\n".join(list)    # Finally, return our list of primes <= i

如果您想提高效率,甚至可以使用range(3, n+1, 2)以2计数-这样就可以避免完全查看偶数。

答案 1 :(得分:0)

如果if/else语句将不会触发break语句中的任何项目都不会执行else块,则可以使用4.4块。 https://docs.python.org/3/tutorial/controlflow.html n = int(input('Enter number: ')) if n <= 1: print('No primes') else: primes = [] for i in range(2, n +1): for k in range(2, i): if not i % k: break else: primes.append(i) print(*primes) # Enter number: 50 # 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 演示了如何完成这项几乎精确的任务。

await sl.TranslateTo(800, 0, 0);
await sl.TranslateTo(0,0,1000);