【问题标题】:How can I jump to another loop?如何跳转到另一个循环?
【发布时间】:2019-01-25 07:52:52
【问题描述】:

我有问题。我不知道如何跳转到另一个循环。我应该在当前循环中使用“继续”还是“中断”? (python3.x)

当真:

当真:

继续

【问题讨论】:

  • 你能分享任何你想要这种操作的代码示例吗?

标签: python python-3.x loops while-loop python-3.7


【解决方案1】:

break 关键字可以让你退出你所在的主循环。所以如果你有这样的语句:

while True:
    while True:
         break

break 会让你回到第一个循环。

【讨论】:

    【解决方案2】:

    你可以打破内循环来继续外循环

    while True:
        while True:
            # do some checks if you want to
            break
    
    

    【讨论】:

      【解决方案3】:

      按照建议使用break,它会在满足条件时退出内部循环。考虑来自[这里https://docs.python.org/3/tutorial/controlflow.html][1]

      的这个例子
      for n in range(2, 10):
       for x in range(2, n):
           if n % x == 0:
               print(n, 'equals', x, '*', n//x)
               break
       else:
           # loop fell through without finding a factor
           print(n, 'is a prime number')
      

      结果 2是质数 3是质数 4 等于 2 * 2 5是质数 6 等于 2 * 3 7是质数 8 等于 2 * 4 9 等于 3 * 3

      【讨论】:

        猜你喜欢
        • 2021-11-04
        • 1970-01-01
        • 2012-06-02
        • 2021-03-30
        • 1970-01-01
        • 2016-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多