关于Python循环的一个简单问题 [英] A simple question about loops in Python
问题描述
我尝试了两个循环样本,但是我知道为什么当loop1从3开始,loop2从2开始? ı应该两者都应该是一样的。
这是输出:
3 prime
4 = 2 * 2.0
5 prime
2 prime
3 prime
4 = 2 * 2.0
5 prime
我尝试了什么:
< pre lang = Python>
def loop1():
表示范围内的n(2,6):
表示范围内的x(2,n):
如果n%x == 0:
print(n,=,x ,*,n / x)
else:
print(n,prime)
break
loop1()
def loop2():
表示范围(2,6)中的c:
表示范围内的k(2,c):
如果c%k == 0:
print(c,=,k,*,c / k)
break
else:
print(c,prime)
loop2()
<二v class =h2_lin>解决方案
第二个循环尝试在第一次迭代中重复范围(2,2)。这是有效的,而x
大于2且小于2:但这是不可能的,因此循环终止。所以当n
的值为3时,输出从3开始,这是外循环的下一次迭代。
如果查看第二个循环的输出,你可以看到第一行输出是:
2 prime
但你知道2不是素数,那么这是怎么发生的?只是因为你的else
子句只缩进一次所以它属于前面的for
语句而不是如果
I've tried two loops samples but ı didint understand why when"loop1" starts from "3", "loop2" starts from "2"? ı supposed that both should have been the same.
Here is the output:
3 prime
4 = 2 * 2.0
5 prime
2 prime
3 prime
4 = 2 * 2.0
5 prime
What I have tried:
<pre lang="Python">
def loop1(): for n in range (2,6): for x in range(2,n): if n % x==0: print(n,"=",x,"*",n/x) else: print(n,"prime") break loop1() def loop2(): for c in range (2,6): for k in range(2,c): if c % k==0: print(c,"=",k,"*",c/k) break else: print(c,"prime") loop2()
The second loop tries to repeat for the range (2,2) in the first iteration. Which is effectively whilex
is greater than 2 and less than 2: but that is impossible so the loop terminates. So the output starts at 3 which is the next iteration of the outer loop whenn
has a value of 3.
If you look at the output from the second loop you can see the first line output is :
2 prime
But you know that 2 is not a prime so how did that happen? Simply because yourelse
clause is only indented once so it belongs to the precedingfor
statement rather than theif
.
这篇关于关于Python循环的一个简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!