我是新手,也是初学者。我需要帮助冷凝play_game()
以下。我需要把它变成18行。我想在此代码中调用if
和else
函数来缩短它的行数。
def play_game(): # def the plag game function which is the main control of the game
level = get_level()
quiz = game_data[level]['quiz']
print quiz
answers_list = game_data[level]['answers']
blanks_index = 0
answers_index = 0
guesses = 3
while blanks_index < len(blanks):
user_answer = raw_input("So what's your answer to question " + blanks[blanks_index] + "? : ") #while, if and else to increment the blanks, answers, and guesses
if check_answer(user_answer,answers_list,answers_index) == "right_answer":
print "\n Lucky Guess!\n"
quiz = quiz.replace(blanks[blanks_index], user_answer.upper()) #prints appropriate responses
blanks_index += 1
answers_index += 1
guesses = 3
print quiz
if blanks_index == len(blanks):
return you_win()
else:
guesses -= 1
if guesses == 0:
return you_lost()
break
print "Incorrect. Try again only " + str (guesses) + " guesses left!"
play_game()
答案 0 :(得分:1)
这里的play_game()
子程序减少到18行代码:
def play_game():
data = game_data[get_level()]
quiz, answers = data['quiz'], data['answers']
index, guesses = 0, 3
print quiz
while index < len(blanks):
user_answer = raw_input("So what's your answer to question " + blanks[index] + "? : ")
if check_answer(user_answer, answers, index) == "right_answer":
quiz = quiz.replace(blanks[index], user_answer.upper())
print "\nLucky Guess!\n\n" + quiz
guesses = 3
index += 1
else:
guesses -= 1
if guesses == 0:
return you_lost()
print "Incorrect. Try again only " + str(guesses) + " guesses left!"
return you_win()
在没有能够实际运行代码的情况下执行。主要是代码清理。