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

Python报错AttributeError:模块‘random’无‘randit’属性,求代码排查

Fixing the AttributeError in Your Number Guessing Game

Hey, let's get that number guessing game up and running! The error you're seeing is a super common typo — easy to miss when you're focused on writing logic.

What's causing the error?

The line secretNumber = random.randit(1, 20) uses randit, but the correct function from the random module is randint (notice the extra 'n' between the 'i' and 't'). Python can't find a function named randit in the random module, hence the AttributeError.

Here's the fixed code with all tiny issues resolved:

I also cleaned up a few other spelling typos that wouldn't break the code but look odd when the game runs:

import random
# Fixed function name from randit → randint
secretNumber = random.randint(1, 20)
# Fixed "nummber" → "number"
print("I'm thinking of a number between 1 and 20.")
for guessesTaken in range(1, 7):
    print("Take a guess.")
    guess = int(input())
    if guess < secretNumber:
        # Fixed "to low" → "too low"
        print("Your guess is too low")
    elif guess > secretNumber:
        # Fixed "to high" → "too high"
        print("Your guess is too high")
    else:
        break  # This condition is the correct guess!
if guess == secretNumber:
    # Added a space before "guesses" for proper formatting
    print("Good job! You guessed my number in " + str(guessesTaken) + " guesses!" )
else:
    # Completed the cut-off message and fixed "numbe" → "number"
    print("Nope. The number I was thinking of was " + str(secretNumber))

Key fixes recap:

  • Replaced random.randit() with random.randint() (the core fix for the AttributeError)
  • Corrected spelling errors: nummber → number, to low → too low, to high → too high
  • Completed the final print statement that was cut off
  • Added a space in the success message to make it read correctly

Now your game should work perfectly — go test it out!

内容的提问来源于stack exchange,提问作者vcosmin2701

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:07:11