2

私は学校のプロジェクトのクイズゲームを作成しています。ユーザーが無効なコマンドを入力すると、戻って入力を再試行してそのメニューに戻り、まったく同じ入力ボックスを表示してコードを試行するようにしたいと思います。また。これを実現したい部分を投稿します。

#---->TO HERE
if userinput == str("help"):
    print ("This is the help menu")
    print ("This is how you play")
else:
    print ("Invalid Command")
#This is where I want the user to go back and try entering a command again to get the same code to run through again. 
#FROM HERE <----
4

3 に答える 3

5
while True:
    userinput = input()
    if userinput == 'help':
        print('This is the help menu')
        print('This is how you play')
        break
    else:
        print('Invalid command')

whileループは、このような状況で使用されます。このステートメントを使用すると、 orループbreakから「抜け出す」ことができます。ステートメントに遭遇しない限り、ループは永久にループします。whileforwhile Truebreak

continueループの残りをスキップして最初に戻るステートメントもありますが、ここでは使用する必要はありません。

詳細については、ドキュメントを参照してください。

于 2013-01-13T03:16:55.737 に答える
2

私はbreaks を使用した無限ループのファンではないので、こちらの方が気に入っています。

validCommands = ['help']
userInput = None
while userInput not in validCommands:
    userInput = input("enter a command: ").strip()
handleInput(userInput)

def handleInput(userInput):
    responses = {'help':['This is the help menu', 'This is how you play']
                }
    print('\n'.join(responses[userInput]))
于 2013-01-13T03:19:59.070 に答える
0
questions = {
    'quiz_question_1': quiz_question_1,
    'quiz_question_2': quiz_question_2
}


def runner(map, start):
    next = start

    while True:
    questions = map[next]
    next = questions()

# whatever room you have set here will be the first one to appear
runner(questions, 'quiz_question_1') 

def quiz_question_1():
 a = raw_input(">")

 if a == "correct answer"
  return "quiz_question_2"

 if a == "incorrect answer"
  return "quiz_question_1"

波括弧内にさらに「部屋」を追加できます。最後の部屋にコンマがなく、コードに表示される順序になっていることを確認してください。

于 2013-01-13T05:30:54.377 に答える