Python中,break和continue的语句只能配合if用吗?

Python中,break和continue的语句只能配合if用吗?
下图来自廖雪峰网站

clipboard.png

阅读 18.1k
2 个回答

不是的,continue和break要在for,while等循环中使用,单独的if语句中不能使用break和continue.
举个例子

# Example 1
for a in [1, 2, 3, 4]:
    if (a == 1):
        continue
    else:
        print(a)
# 2
# 3
# 4
# Example 2
for a in [1, 2, 3, 4]:
    print(a)
    continue
    

单独的if不能使用continue和break

# Example 3
if True:
    continue
# SyntaxError: 'continue' not properly in loop
    

当然不是,break和continue用来跳出循环

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题