首页 > 解决方案 > 找到素数,我写了一个不正确的函数和一个正确的函数。但我不确定为什么一个是正确的,一个是不正确的

问题描述

所以这个想法是创建一个函数来返回任何两个数字(包括)之间的所有素数。下面,我将把我写正确的函数和我写错的函数放在一起。

我犯的错误是“else”语句的缩进。但我不确定为什么一个是正确的,另一个是不正确的!

我也很好奇我从不正确的函数中得到的输出,它主要显示素数的重复,但偶尔会抛出一个不是素数的数字,而是一个可被 3 整除的数字和另一个素数。我一直试图弄清楚函数是如何产生这个结果的(所以我可以理解这个错误),但我很难过!

任何帮助将非常感激

##This is the correct version: ##########################

def primefinder(start, end):                   
    primes = []
    for number in range(start, end +1):
        if number > 1:
            for i in range(2, number):
                if number % i == 0:
                    break
            else:                            
                primes.append(number)
    return primes


## This is the incorrect version:##############

def primefinder(start, end):
    primes = []
    for number in range(start, end +1):
        if number > 1:
            for i in range(2, number):
                if number % i == 0:
                    break
                else:                     ##<--This is my mistake##
                    primes.append(number)
    return primes

标签: pythonfunctionloopsprimes

解决方案


任何帮助将非常感激

如有疑问,您可以help在交互模式下使用。在这种情况下,启动 python 并help("for")获取以下信息:

The "for" statement
*******************

The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:

   for_stmt ::= "for" target_list "in" expression_list ":" suite
                ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object.  An iterator is created for the result of the
"expression_list".  The suite is then executed once for each item
provided by the iterator, in the order returned by the iterator.  Each
item in turn is assigned to the target list using the standard rules
for assignments (see Assignment statements), and then the suite is
executed.  When the items are exhausted (which is immediately when the
sequence is empty or an iterator raises a "StopIteration" exception),
the suite in the "else" clause, if present, is executed, and the loop
terminates.
...

依此类推,请注意,这仅在迭代因耗尽而结束时才有效,而不是当您break从循环中 -ed 时才有效。考虑到

for x in [1,2,3]:
    print(x)
else:
    print("else")

最后将打印“else”,而

for x in [1,2,3]:
    print(x)
    break
else:
    print("else")

将不会。


推荐阅读