You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 count variable: You're incrementing count throughout the game but never set it to 0 at the start of play_game(). Python will throw a NameError when it tries to use count for the first time.
  • Incorrect condition order: Your elif guess >= number will catch cases where guess == number first, so the final elif guess == number block 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 = 0 at the start of play_game() to track the number of guesses.
  • Moved count += 1 to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:19:21