Python问答游戏代码优化求助:如何让代码更整洁可读并运用内置函数
Python问答游戏代码优化求助:如何让代码更整洁可读并运用内置函数
Hey there! Nice start on your quiz game—let's clean this up and make use of those handy built-in functions you want to learn. I'll walk through key improvements and show you a revised version with explanations:
Key Improvements & Built-in Functions Used
enumerate(): Tracks question numbers automatically without manually incrementing a counterzip(): Pairs questions, answers, and options together neatlydict.values(): Gets all correct answers in one gozip()again: Compares user guesses to correct answers side-by-side in the score display
Revised Code
def new_game(): guesses = [] correct_guesses = 0 # Use enumerate to get question number, and zip to pair questions/answers with options for question_num, ((question, correct_answer), options_list) in enumerate(zip(questions.items(), options), start=1): print('---------------------------------------------------------') print(f"Question {question_num}: {question}") for option in options_list: print(option) guess = input("Enter (A, B, C or D): ").upper() guesses.append(guess) # Check answer and update score is_correct = check_answers(correct_answer, guess) correct_guesses += is_correct display_score(correct_guesses, guesses) def check_answers(correct_answer, user_guess): if correct_answer == user_guess: print("CORRECT") return 1 else: print("WRONG") return 0 def display_score(correct_guesses, user_guesses): print("\n-----------------------------------------") print("RESULT:") print("-----------------------------------------") # Get all correct answers once with dict.values() correct_answers = list(questions.values()) # Use zip to show guesses vs correct answers in one loop print("Answers vs Your Guesses:") for ans, guess in zip(correct_answers, user_guesses): print(f"Correct: {ans} | Your Guess: {guess}") # Calculate and display percentage score score = int((correct_guesses / len(user_guesses)) * 100) print(f"\nYour Score: {score}%") def play_again(): play = input("\nDo you wanna play again (y/n)? ").lower().strip() # Fix: properly return False instead of just having it in the else block return play == "y" # Game data questions = { "Who created Python? ": "B", "From where is the name 'Python' originating? ": "C", "What year did World War II start? ": "A", "What was Usain Bolt's 100m time in 2009? ": "C" } options = [ ['A. Bjarne Stroustrup', 'B. Guido Van Rossum', 'C. Alexander Cobol', 'D. Blaise Pascal'], ['A. From the python snake', 'B. From his mother’s heart disease', 'C. From music band Monty Python', 'D. None'], ["A. 1939", "B. 1969", "C. 1200 A.D.", 'D. 2001'], ['A. 9.2', 'B. 7.67', 'C. 9.58', 'D. 10.05'] ] # Start the game new_game() while play_again(): new_game() print("\nBye!")
Let's Break Down the Changes
Simplified Question Loop:
- We use
zip(questions.items(), options)to pair each question-answer pair with its corresponding options list. enumerate(..., start=1)gives us the question number directly (starting at 1 instead of 0), so we don't need to trackquestion_nummanually.
- We use
Cleaner Score Display:
questions.values()grabs all correct answers in one line instead of looping through the dict keys.zip(correct_answers, user_guesses)lets us print each correct answer next to the user's guess in a single loop—no more separate loops!
Fixed Play Again Function:
- The original function didn't return
Falseproperly; now it returns a boolean directly based on the user's input. - Added
.strip()to handle accidental spaces in the input.
- The original function didn't return
Readability Tweaks:
- Renamed variables for consistency (e.g.,
user_guessesinstead ofguessin display_score). - Used f-strings for clearer print statements (like showing the question number).
- Renamed variables for consistency (e.g.,
This version is more efficient, easier to read, and makes heavy use of those useful built-in functions you wanted to learn. Let me know if you have any questions about how any part works!
备注:内容来源于stack exchange,提问作者teddy
相关产品推荐
相关产品推荐

