首页 > 解决方案 > 在终端控制台中,如何使用 python 结束/关闭循环?(我想运行循环,请不要错误结束循环)

问题描述

使用终端控制台时,我想在 for 循环中快速测试一个变量。但不知道如何“关闭”循环。它让我一直要求下一行代码。

>>> for i in z:
...     print(i)
...

在终端中,当我开始在循环中编写第二行时,它以'...'开头,无论我按回车多少次,循环仍然没有结束并以'...'开头。我发现退出循环的唯一可能方法是创建一个错误。但是我想在终端中结束循环,同时能够运行它。

标签: python-3.x

解决方案


从你那里收集到一些可能性,所以我只讨论其中的一些。对于特定答案,更好的细节仍然有用:

# This is if you want to run the loop 5 times
for i in range(5):
    print(i)

# For breaking out of the loop but not the program
for i in range(5):
    print(i)
    if(i==2):
        break
# For breaking out of the program, with exit command and not error
for i in range(5):
    print(i)
    if(i==2):
        exit()


for i in range(8):
...     print(i)
... <Here you press enter without tab to exit out of loop>

基于编辑的评论:这是添加的代码:for i in range(8): ... print(i) ...


推荐阅读