Python:素数和inrange() [英] Python: Prime numbers and the in range()
问题描述
我正在学习python并正在研究此问题: Python-素数练习 这是我的问题: 当n = 2时,范围为(2,n),换句话说,范围在2到2-1 = 1之间.
I am learning python and was looking at this problem: Python - Prime Number exercise Here are my questions: When n=2, the range will be (2,n), in the other words the range is between 2 and 2-1=1.
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
return False
else:
print(n, "is a prime number")
return True
a.会是2%2吗?
b.如果数字是偶数,它将打印
b. If the number is even, it will print
A等于B x C
A equals B x C
条件成立时,循环会中断吗?还是会结束循环?
will the loop break once the condition is true or it will finish the loop?
c.循环之外的其他东西吗? if语句对应什么? (我知道它是if n % x == 0:
),但是看起来好像在循环之外呢?
我试图运行它,并且理解了,但是后来我感到困惑.
c. is the else outside the loop? what if statement does it correspond? (i know it is the if n % x == 0:
) but howcome it is seems like it is outside the loop?
I tried to run it, and understand, but then I got confused.
推荐答案
for .. else混乱
您似乎对for
循环的一部分else
感到困惑.
for .. else confusion
You seem to be confused by else
which is part of the for
loop.
您不是唯一的一个人.
在Python中,除非存在break
语句,否则for
循环可能在else
节的末尾,该节在所有循环完成后才执行.是的,不是很直观.
In Python, for
loop might have at the end else
section, which is executed after all the loops are finished, unless there was break
statement. Yes, it is not very intuitive.
因此,您应该在for
循环的最后部分阅读else
部分.
So you shall read the else
section as last part of the for
loop.
def looptest(loops=5):
for i in range(loops):
print "i", i
if i == 3:
print "in if"
return
else:
print "in else of the loop"
并尝试循环== 5:
>>> looptest(5)
i 0
i 1
i 2
i 3
in if
对于循环2的数量,我们不希望返回,我们将在循环的else
中运行:
For number of loops 2 we do not expect return, we shall run through else
of the loop:
>>> looptest(2)
i 0
i 1
in else of the loop
请注意,return
必须在函数内,尝试在控制台上返回会导致错误.
Note, that return
must be within function, trying return on console would result in error.
在Python控制台上尝试:
Trying on Python console:
>>> range(2, 2)
[]
返回
return结束当前功能或在整个模块中运行.因此,在return
之后,将不再执行代码同一部分中的其他代码(try
,finally
,上下文管理器等例外,但这与您的代码无关).
return
return ends up current function or run in the whole module. So after return
, no further code in the same part of your code is executed (with exceptions like try
, finally
, context managers etc, but this is not relevant to your code).
这篇关于Python:素数和inrange()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!