鱼C论坛

 找回密码
 立即注册
查看: 3675|回复: 2

[已解决]求助!

[复制链接]
发表于 2023-1-13 18:40:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
请问,如何一次性退出多层循环?
(实际情况:做pygame的时候有多个窗口(不同时出现),有先后关系)
注:针对大部分情况,故不附代码

最佳答案
2023-1-13 18:48:46
本帖最后由 isdkz 于 2023-1-13 19:08 编辑

三种办法:

一、可以用抛出异常来实现

参考代码:
  1. try:
  2.     while True:
  3.         while True:
  4.              while True:
  5.                 print('直接退出多层循环')
  6.                 raise Exception
  7. except:
  8.     print('多层循环被退出了')
复制代码


二、封装成函数,使用 return

参考代码:
  1. def test():
  2.     while True:
  3.         while True:
  4.             while True:
  5.                 print('直接退出多层循环')
  6.                 return
  7. test()
  8. print('多层循环已经被退出了')
复制代码


三、利用循环的 else 语法和 continue 结合(这个需要慢慢消化,理解了循环的 else 用法就能理解为什么可以这样子了):

参考代码:
  1. while True:
  2.     while True:
  3.         while True:
  4.             print('直接退出多层循环')
  5.             break
  6.         else:
  7.             continue
  8.         break
  9.     else:
  10.         continue
  11.     break
  12. print('多层循环已经被退出了')
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-1-13 18:48:02 | 显示全部楼层
  1. try:
  2.     while True:
  3.         try:
  4.             while True:
  5.                 try:
  6.                     while True:
  7.                         x = int(input('想要跳出几层循环:'))
  8.                         if x == 1:   raise TypeError
  9.                         elif x == 2: raise ZeroDivisionError
  10.                         elif x == 3: raise ValueError
  11.                 except TypeError:
  12.                     print('1')
  13.         except ZeroDivisionError:
  14.             print('2')
  15. except ValueError:
  16.     print('3')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-1-13 18:48:46 | 显示全部楼层    本楼为最佳答案   
本帖最后由 isdkz 于 2023-1-13 19:08 编辑

三种办法:

一、可以用抛出异常来实现

参考代码:
  1. try:
  2.     while True:
  3.         while True:
  4.              while True:
  5.                 print('直接退出多层循环')
  6.                 raise Exception
  7. except:
  8.     print('多层循环被退出了')
复制代码


二、封装成函数,使用 return

参考代码:
  1. def test():
  2.     while True:
  3.         while True:
  4.             while True:
  5.                 print('直接退出多层循环')
  6.                 return
  7. test()
  8. print('多层循环已经被退出了')
复制代码


三、利用循环的 else 语法和 continue 结合(这个需要慢慢消化,理解了循环的 else 用法就能理解为什么可以这样子了):

参考代码:
  1. while True:
  2.     while True:
  3.         while True:
  4.             print('直接退出多层循环')
  5.             break
  6.         else:
  7.             continue
  8.         break
  9.     else:
  10.         continue
  11.     break
  12. print('多层循环已经被退出了')
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 19:26

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表