嵌套函数

Nested functions

我正在学习 Python,我目前有一个函数很长而且有些重复。请看下面:目标: 将函数分解成多个部分,以便我更好地理解这个过程如何工作。

def play_game(questions,answers):
    '''Begins checking user input to answers /
       fills in the blanks with correct answer /
       prompts user with same question if answer is Wrong
       :param questions: feeds .split() list to find __1__
       :param answers: searches for answer and replaces blank __1__
       :return: replaces correct answer in questions param.
       '''
    print questions
    user_input = raw_input("Fill in the blank: ")
    if user_input == answers[0]:
        questions = questions.replace('__1__', answers[0])
    if user_input != answers[0]:
        user_input = raw_input("Wrong answer, you have 4 guesses left. ")
    print questions
    user_input = raw_input("\n Please answer second question: ")
    if user_input == answers[1]:
        questions += questions.replace('__2__', answers[1])
    if user_input != answers[1]:
        user_input = raw_input("\n Incorrect, you have 3 guesses left. ")
    print questions

这个过程将持续进行 5 次猜测。我想强调的是,如果用户猜错了,再次询问同一个问题的重要性,他们的猜测也会从 5 减少到 4,等等。我应该在这里使用循环来自动化吗?

print questions
#for answer in answers:
# process answer
user_input = raw_input("Fill in the blank: ")
if user_input == answers[0]:

尝试这样的事情:

for guess in range(4):
    print "Guess", guess + 1

# Put your game function here

    if guess == 3:
        print "Game Over!"