2017-08-16 55 views
-4

我是新手和初學者。下面我需要幫助冷凝play_game()。我需要把它弄到18行。我想在這段代碼中調用ifelse函數來縮短它很多行。Python代碼縮合

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() 
+2

這不是這個問題的正確的地方。嘗試發佈代碼審查。 – Julien

+2

嗯...... 18行?爲什麼18? –

+0

我正在通過一堂課,那就是我正在反饋的反饋 – Tadpole

回答

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() 

整蠱而不能實際運行代碼來執行。大多隻是代碼清理。