Python代码运行报错TypeError:play_game()缺少必需参数limit
Hey there! Let's break down what's going wrong with your guess-the-number game and fix it step by step.
1. The Immediate Error: Missing Argument
The TypeError: play_game() missing 1 required positional argument: 'limit' is easy to spot. In your main() function, you're calling play_game() without passing the limit variable you just retrieved from get_limit(). You need to update that line to:
play_game(limit)
2. Hidden Bugs That Would Break the Game Next
Even after fixing the argument issue, your code will hit more problems:
- Uninitialized
countvariable: You're incrementingcountthroughout the game but never set it to 0 at the start ofplay_game(). Python will throw aNameErrorwhen it tries to usecountfor the first time. - Incorrect condition order: Your
elif guess >= numberwill catch cases whereguess == numberfirst, so the finalelif guess == numberblock will never run. This means the game will never recognize a correct guess.
3. Fixed Full Code
Here's the corrected version with all issues resolved:
#!/usr/bin/env python3 import random def display_title(): print("Guess the number!") print() def get_limit(): limit = int(input("Enter the upper limit for the range of numbers: ")) return limit def play_game(limit): number = random.randint(1, limit) print(f"I'm thinking of a number from 1 to {limit}\n") count = 0 # Initialize the guess counter while True: guess = int(input("Your guess: ")) count += 1 # Increment count for every valid guess if guess < number: print("Too low.") elif guess > number: print("Too high.") else: # Guess matches the target number print(f"You guessed it in {count} tries.\n") return def main(): display_title() again = "y" while again.lower() == "y": limit = get_limit() play_game(limit) # Pass the required limit argument again = input("Play again? (y/n): ") print() print("Bye!") if __name__ == "__main__": main()
Quick Fix Breakdown:
- Added
count = 0at the start ofplay_game()to track the number of guesses. - Moved
count += 1to run right after getting a guess, so every attempt (including the correct one) is counted. - Adjusted the condition order to check for too low → too high → correct guess, ensuring the winning case is triggered properly.
- Used f-strings for cleaner, more readable string formatting instead of concatenating with
+.
内容的提问来源于stack exchange,提问作者hts95
相关产品推荐
相关产品推荐

