嵌套函数

时间:2016-07-22 14:38:17

标签: python python-2.7 data-analysis

我正在学习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]:

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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

# Put your game function here

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