【问题标题】:How does python know when to stop the for loop?python如何知道何时停止for循环?
【发布时间】:2018-10-17 10:34:19
【问题描述】:

第一次在 python 中编程 python 如何知道何时停止 for 循环? 像 for 没有匹配的结尾正确吗?那么它如何知道什么是循环的一部分,什么不是呢? 抱歉,如果这是个愚蠢的问题,我找不到答案

【问题讨论】:

  • 缩进,就像 Python 中的其他一切一样。如果它是缩进的,它是上面缩进较少的任何内容的一部分。
  • Python 依赖于代码块的缩进,因此它可以根据代码的缩进和不缩进知道循环的代码块在哪里结束。

标签: loops for-loop while-loop infinite-loop


【解决方案1】:

Python 严重依赖缩进

# Below prints 1-5, sees that the next for line is not indented, doesn't read it
for x in range(5):
    print(x)

# there are other methods of breaking a python loop
for x in range(6):
    print(x)
 if x == 5:
         # break the loop
         break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2021-04-16
    相关资源
    最近更新 更多