Python 2.7退出

2024-10-01 17:35:11 发布

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

我添加了这个函数,确保用户确实想退出程序。当您确实想退出时,它可以工作,但如果您想返回程序,它只会循环语句:

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()

其他地方:

^{pr2}$

Tags: to函数用户程序youinputrawreturn
3条回答

您可以使用一个已经定义的函数quit(),而不是创建一个新函数。quit函数将弹出一个框,其中说明:

[英寸]

quit()

[出去]

Your program is still running!
Do you want to kill it?
    Yes    No

print ('')替换为{},并删除{}。在

我还建议您对您的.lower()变量应用.lower(),这样它就不区分大小写了。在

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

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

我会这样做:

^{pr2}$

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

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()立即退出。在

第一种可能更可取,尽管这两种方法都在实践中使用。在

相关问题 更多 >

    热门问题