0

我在这个函数中添加了确保用户确实想要退出程序的功能。它在您真正想退出时起作用,但如果您想返回程序,它只会循环语句:

def WantToQuit():
    Quit = raw_input("Please enter y if you are sure you want to quit, if not press n to return ")
    if Quit == 'y':
        print ('')
    elif Quit == 'n':
        DisplayMenu()
        return WantToQuit()

别处:

elif Choice == 'q':
    WantToQuit()
    raw_input('Press enter key to continue ')
4

3 回答 3

5

替换print ('')sys.exit (0)并删除return WantToQuit().

我还建议您应用.lower()您的Quit变​​量,使其不区分大小写。

于 2013-03-22T10:30:38.193 回答
1

如果没有更多代码,很难向您展示您做错了什么,但我认为您的设置如下:

def WantToQuit():
    Quit = raw_input("Please enter y if you are sure you want to quit, if not press n to return ")
    if Quit == 'y':
        print ('')
    elif Quit == 'n':
        DisplayMenu()
    return WantToQuit()

while(True):
    DisplayMenu()
    # Some logic to get input and handle it
    # For example, something like
    selection = raw_input("Please make a selection: ")
    if(selection == "1"):
        doSomething()
    elif(selection == "2"):
        doSomethingElse()
    elif(selection == "q"):
        WantToQuit()
    else:
        # TODO: Handle this !
        pass

我会这样做:

def WantToQuit():
    Quit = raw_input("Please enter y if you are sure you want to quit, if not press n to return ")
    if Quit == 'y':
        return true
    elif Quit == 'n':
        return false
    else:
        # TODO: Handle this !
        pass

while(True):
    DisplayMenu()
    # Some logic to get input and handle it
    # For example, something like
    selection = raw_input("Please make a selection: ").lower()
    if(selection == "1"):
        doSomething()
    elif(selection == "2"):
        doSomethingElse()
    elif(selection == "q"):
        if(WantToQuit()): break
    else:
        # TODO: Handle this !
        pass

或者,您可以执行以下操作:

def WantToQuit():
    Quit = raw_input("Please enter y if you are sure you want to quit, if not press n to return ")
    if Quit == 'y':
        sys.exit(0)
    elif Quit == 'n':
        return # Do nothing really
    else:
        # TODO: Handle this !
        pass

while(True):
    DisplayMenu()
    # Some logic to get input and handle it
    # For example, something like
    selection = raw_input("Please make a selection: ").lower()
    if(selection == "1"):
        doSomething()
    elif(selection == "2"):
        doSomethingElse()
    elif(selection == "q"):
        WantToQuit()
    else:
        # TODO: Handle this !
        pass

第一个示例让WantToQuit函数返回一个布尔值,用户是否真的想退出。如果是这样,无限循环被打破,程序自然退出。

第二个例子处理WantToQuit函数内部的退出,调用sys.exit()立即退出。

第一个可能更可取,尽管两者都在实践中使用。

于 2013-03-22T10:32:49.650 回答
0

您可以使用已经定义的函数,而不是创建一个新函数quit()。该quit函数会弹出一个框,上面写着:

[在]

quit()

[出去]

Your program is still running!
Do you want to kill it?
    Yes    No
于 2016-07-11T17:18:30.423 回答