在Python中中断while循环

2024-09-30 20:27:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

目前,这是我唯一能做到的方法(如果用户在每一点后都输入了“--back”语句)。这个菜单代码从返回菜单.解析如果它被改变了。但在新菜单代码生效之前,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':
                    ...

Tags: selfnewinputifparsemaindef菜单
3条回答

对于这个特定的代码,@kris使用异常的建议可能是合理的。不过,如果你想更深入地研究一下状态机。看起来你的应用程序本质上是一个状态机,并且,通过使用状态机来处理从一个状态到另一个状态的转换,你可以使你的代码更容易理解,更重要的是,当有人想向它添加另一个命令时,你可以更容易地在六个月内返回。在

要打破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()

引发异常以退出循环。这在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

但在这种情况下,从menu类的内部引发异常肯定会更自然。在

用Python很容易做到。缺点是这会使代码流稍微难以理解,但您的示例看起来确实是异常的合法使用。在

相关问题 更多 >