Python break语句详细信息

时间:2017-02-28 06:27:40

标签: python break

有人可以向我提供有关此问题的详细信息吗?

for i in range(1,10):
      if i == 5:
           break
      print("number is ", i)


Output:
number is 1
number is 2
number is 3
number is 4

我的问题是:为什么没来5?我在这里告诉我= = 5这意味着当我的价值是5然后它应该打破并给出结果5。

now,  if i > 5:
         break
    print(i)
Output: 
     number is 1
     number is 2
     number is 3
     number is 4
     number is 5

这里5> 5事实并非如此。那怎么样?

最后一件事如果结构

for i in range(1,10):
print(i)
if i < 5:
    break

 Output: only 1 

问题:结果至少应该是1到4。但不是为什么?

感谢所有人。希望您能理解并向我详细说明我的问题。

2 个答案:

答案 0 :(得分:3)

为什么它不打印5的原因是因为你在到达print("number is ", i)之前制动了循环。

for i in range(1,10):
      if i == 5: #when i is 5 this will be true
           break #break the loop exits the loop
      #----------------------This is not run when i==5 because the loop already ended
      print("number is ", i)

如果你想打印5

for i in range(1,10):

     print("number is ", i) #put this in front
     if i == 5: #when i is 5 this will be true
           break #break the loop exits the loop

作为旁注:range(1,10)实际上是[1,2,3,4,5,6,7,8,9],因为python跳过最后一个而不包含10个

致OP评论:

for i in range(1,10):

     if i > 5: #when i is 5 this will be false, so the loop doesn't break
           break #break the loop when i > 5 (ie. 6) so now the print() isn't reached and will not print 6

     print("number is ", i) #since the loop didn't break when i is 5, it printed i

还有其他两个新例子:

for i in range(1,10):
    if i > 5:
         break #exits here skips the print since it's after this
    print(i) #the print statement is here so when i > 5 this is not reached
#on the other hand:
for i in range(1,10):
    print(i) #the print statement is in front of the break statement so now it will print 6 too since the loop hasn't break yet
    if i > 5:
         break #exits here after the print()
#output also includes 6

最后一件事如果结构

for i in range(1,10):
    print(i) #only 1 got printed since the loop break before it get to 2
    if i < 5: #when i < 5 so it breaks in the first loop when i is 1
        break #exits the loop

您可能需要查看this 并查看是否有帮助

答案 1 :(得分:0)

在i = 5迭代中,您传递if测试的条件并执行语句的then块,其中包含break。 break语句会导致您退出循环。 print语句是循环体的一部分,在i = 5的迭代中永远不会到达。