在Python中打破while循环

时间:2012-03-08 22:28:08

标签: python while-loop break

我有一个正在读取用户输入的while循环。但我希望用户能够在任何时候打破while循环,这样他们就可以返回主菜单。

目前这是我能做到的唯一方法(如果用户可能输入'--back'的每一点之后的语句。如果更改了menu.code,则从menu.parse函数返回。但是,在新的菜单代码生效之前,while循环必须完全完成。有没有办法在没有所有if语句的情况下执行此操作?

menu是一个班级,还有其他一些班级。以下是主循环的一部分。

一些菜单类:

class Menu:

    def __init__(self):
                self.code = 'main'
                self.codememory = []

    def exit(self, input):
        if input == '--exit':
            sys.exit()

    def back(self, input):
        if input == '--back':
            if 'main' in self.codememory:
                print "should be going back"
                print self.code
                self.code = self.codememory.pop()
                print self.code

    def move(self, input):
        if input == '--new':
            self.codememory.append(self.code)
            self.code = 'new'
        if input == '--main':
            self.codememory.append(self.code)
            self.code = 'main'
        if input == '--help':
            self.codememory.append(self.code)
            self.code = 'help'

    def select(self, input):
        if input in string.digits:
            input = int(input)
            if input == 1:
                self.codememory.append(self.code)
                self.code = 'new'
            if input == 2:
                self.codememory.append(self.code)
                self.code = 'test'

    def header(self, title):
        os.system('clear')
        print "-------------------"
        print title.upper()
        print "-------------------"
        print ""

    def parse(self, input):
        self.exit(input)
        self.back(input)
        if self.code == 'new':
            return input.lower().decode('utf-8')

############################
   menu = Menu()



        while 1:

            ...

            while menu.code == 'new':
                    menu.header('save word')
                    key = menu.parse(raw_input("Norwegain: "))
                    while key in dict.keys:
                        print "word already Saved in Dictionary"
                        key = menu.parse(raw_input("Norwegain: "))
                    if menu.code == 'new':
                        val = menu.parse(raw_input("English: "))
                    if menu.code == 'new':
                        syn = menu.parse(raw_input("Synonym: "))
                    if menu.code == 'new':
                        ant = menu.parse(raw_input("Antonym: "))

            while menu.code == 'main':
                    ...

3 个答案:

答案 0 :(得分:3)

要在Python中打破多个循环,将循环包装在一个函数中,并在您想要离开时从它返回:

while 1:
    def donew():
       while menu.code == 'new':
          blah ...
          while key in dict.keys:
             blah ...
             if some_condition: return
          blah ...
          val = menu.parse(raw_input("English: "))
    donew()

答案 1 :(得分:1)

引发异常以退出循环。这是Python中常见的技巧,你描述问题的方式让我相信它实际上是你愿意管理的一种例外。

代码可能如下所示:

class OutMainLoop(Exception):
    pass

while 1:
    try:
       while menu.code == 'new':
          blah ...
          while key in dict.keys:
             blah ...
             if some_condition:
                raise OutToMainLoop()
          blah ...
          val = menu.parse(raw_input("English: "))
    except OutToMainLoop:
        pass

但是在这种情况下,从里面菜单类中引发异常肯定会更自然。

在Python中很容易做到。缺点是使代码流程稍微难以遵循,但您的示例看起来真的是合法使用异常。

答案 2 :(得分:1)

有了这个特殊代码,@ kriss'建议使用例外可能是合理的。为了更多元,你可能想要研究状态机。看起来您的应用程序本质上是一个状态机,并且通过使用状态机来处理从一个状态到另一个状态的转换,您可以使代码更容易遵循,更重要的是,更容易在六个月内恢复当有人想要添加另一个命令时。

相关问题