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循环用于此类情况。该break语句允许您“跳出”whilefor循环。除非遇到语句while True,否则循环将永远循环。break

还有一个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 回答