【问题标题】:Python: Break vs fulfilling while loop condition? [duplicate]Python:打破与满足while循环条件? [复制]
【发布时间】:2016-01-20 13:31:46
【问题描述】:

我知道要停止迭代 while 循环,您可以满足条件,也可以使用 break 命令。例如

apples = 10

while apples > 0:
    apples -= 1  

while True:
   if apples == 0:
      break
   else:
      apples -= 1

但这显然是一个非常基本的示例,我不确定在更大的代码示例中哪个更有用、更简单或更专业。我觉得这可能最终会更多地成为一种情况,但是,我似乎无法在谷歌上找到答案。谢谢。

编辑:

在过去的项目中使用第一个例子的例子:

finished_adding_object = False             

        while finished_adding_object == False:

            print "System >>> Please enter new " + cls.__name__ + " name. If the user doesn't want to create a new " + cls.__name__ + ", please enter \"exit\"."   
            pending_new_object = raw_input("User >>> ")

            while pending_new_object == "exit":                                       

                print "System >>> Please confirm, the user wishes to abandon creating a new " + cls.__name__ + "? (y/n)"
                abandon_confirmation = raw_input("User >>> ")

                if abandon_confirmation == "y":                             

                    pending_new_object = None
                    finished_adding_object = True

                elif abandon_confirmation == "n":                                                      

                    pending_new_object = None

                elif abandon_confirmation != "n" or "y":  # User told if input is invalid.               

                     print "System >>> " + abandon_confirmation + " is an invalid command."  

【问题讨论】:

  • 在如此多不同的情况下,有如此多不同的方法可以做到这一点,以至于不可能说哪一种是“最好的”。 “最佳”解决方案通常是最易读的,对特定情况有意义的解决方案。

标签: python while-loop conditional-statements break


【解决方案1】:

我会说大多数时候这是个人代码概念。

如果我不想要无限循环,我习惯于在您的第一个示例中执行相同的操作,因为我认为它更具可读性,并且您很快就会明白为什么要离开循环。

【讨论】:

  • 我通常也会实现我的第一个示例,原因完全相同。然而,查看一个严重依赖用户输入的旧项目,如果我使用第二个示例,我的代码似乎不会那么混乱。这只会增加我的困惑哈哈。
  • 我很好奇,你能把第一个解决方案弄乱的代码贴出来看看它是什么样子吗?
  • 编辑它,因为我无法在评论中发布代码:P。
  • 是的,我不知道中断状态是否会使其更具可读性。我想它需要被分解为可读的功能。
  • 这是我考虑的另一种可能性。但是我担心我最终会过度概括我的代码。虽然它肯定会很容易阅读,但这是肯定的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 1970-01-01
  • 2021-12-14
  • 2015-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多