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に終了するかどうかにかかわらず、関数がブール値を返します。その場合、無限ループが中断され、プログラムは自然に終了します。

2番目の例では、関数内の終了を処理し、すぐに終了する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 に答える