简体   繁体   English

另一个For循环中的For-Else循环

[英]For-Else loop in another For loop

I have some question regarding the for-else loop in another for loop. 我对另一个for循环中的for-else循环有一些疑问。 So here is an example: 所以这是一个例子:

primelist = []
for p in range (2, x+1):
    print 'in first for'
    raw_input()
    for i in range(2, p):
        print 'in second for'
        if p%i == 0:
            print 'in if'
            raw_input()
            break
    else:
        print 'in else'
        raw_input()
        primelist = primelist + [p]
return primelist

As you see this is for determining the prime numbers and store them into a list so that they can be retrieved later. 如您所见,这是用于确定质数并将其存储在列表中的,以便以后可以检索。 So my problem is with the first for loop. 所以我的问题是第一个for循环。 When I run the program, it enters like this: First FOR loop, ELSE, First FOR loop, Second FOR loop and so on. 当我运行该程序时,它的输入如下:First FOR循环,ELSE,First FOR循环,Second FOR循环等等。 Why does it skip to ELSE the first time? 为什么它第一次跳到ELSE? Also if I ask for the 1000th number I get : 7919 with the 另外,如果我要求输入第1000个数字,则输入:7919

for i in range(2, p)

and 7907 with the 和7907与

for i in range(2, p/2).

Why is that? 这是为什么? Hope you will help me with this, but please do not give other methods for implementing the Prime Number algorithm! 希望您能对此有所帮助,但请不要提供其他实现素数算法的方法!

Python's range doesn't include the ending value. Python的range不包含结束值。

range[start, end)

So, In the first iteration, value of p will be 2 and range(2, 2) is an empty list. 因此,在第一次迭代中, p值为2, range(2, 2)为空列表。 That is why the else part is entered. 这就是为什么要输入else部分的原因。

print range(2, 2)  # []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM