对于以下程序,我知道它们是无效的,但我正在询问代码的逻辑。我并不打算运行这段代码,只是想知道它将打印的输出,以及continue/break的功能。我很感激你对这件事的反馈/评论/关心。
for x in [1, 1, 2, 3, 5, 8, 13]:
if 1 < x < 13:
continue
else:
print x
输出不应该是:2,3,5,8,因为它们在1
found = False
for n in xrange(40,50):
if (n / 45) > 1:
found = True
break
print found
我想它会输出46,47,48,49,50。但是代码中的中断,仅仅是暂停了这个过程吗?
在第一个循环中,continue
语句跳过循环体的其余部分,以'继续'下一次迭代。由于1
和13
不匹配1 < x < 13
链式比较,因此只实际打印前2和最后一个值,其余的将被跳过。
这里continue
并不重要,print
只在else
套件中执行无论如何;你也可以用pass
代替continue
:
for x in [1, 1, 2, 3, 5, 8, 13]:
if 1 < x < 13:
pass
else:
print x
或使用if not (1 < x < 13): print x
在第二个循环中,break
结束整个循环。没有数字被打印(没有print n
),只有print found
语句打印的False
。这是因为在Python 2中,带整数的/
只给你层除法,所以if
语句永远不会为真(只有当n = 90
或更大时,n / 45
才会变成2
或更大)。
对这两个语句更好的说明是在循环之前,在语句前后的循环中使用print
,然后打印出来,这样您就可以看到在以下情况下执行了什么代码:
print 'Before the loop'
for i in range(5):
print 'Start of the loop, i = {}'.format(i)
if i == 2:
print 'i is set to 2, continuing with the next iteration'
continue
if i == 3:
print 'i is set to 3, breaking out of the loop'
break
print 'End of the loop'
print 'Loop has completed'
输出:Start of the loop, i = 0
End of the loop
Start of the loop, i = 1
End of the loop
Start of the loop, i = 2
i is set to 2, continuing with the next iteration
Start of the loop, i = 3
i is set to 3, breaking out of the loop
Loop has completed
注意i = 2
后面没有End of the loop
,根本没有i = 4
continue
导致程序跳到循环的下一次迭代。因此,第一个块将打印1 1 13,因为只有这些元素不满足if
条件。
break
终止了一个循环,因此第二个代码片段的循环似乎应该在46处终止。然而,由于python中的整数除法只保留整个部分,因此该循环将不间断地持续到范围的末尾。