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

Python报错AttributeError: module 'random' has no attribute 'randint'求助

Fixing AttributeError: module 'random' has no attribute 'randint'

Hey there! Let's break down why this error is popping up and how to fix it in no time.

The Root Cause

Your script file is named random.py—this is conflicting with Python's built-in random module! When you run import random, Python checks the current directory first for modules, so it's importing your own script instead of the standard library's random module. Since your script doesn't have a randint function defined, you get that AttributeError.

Here's How to Fix It

  • Rename your script: Change the filename from random.py to something that doesn't clash with Python's standard modules, like turtle_random_dots.py.
  • Clean up cached files: If there's a random.pyc file in your directory (this is a compiled bytecode file), delete it—this ensures Python doesn't keep using the old cached version of your script.
  • Re-run your script: Now when you do import random, Python will correctly load the standard library module, and random.randint() will work as expected.

Your Original Code (for reference)

import turtle
import random
turtle.penup()
for i in range(20):
    x=random.randint(-200,200)
    y=random.randint(-200,200)
    turtle.setposition(x,y)
    turtle.dot()
turtle.done()

The Error You Saw

F:\Python>random.py
Traceback (most recent call last):
File "F:\Python\random.py", line 2, in
import random
File "F:\Python\random.py", line 5, in
x=random.randint(-200,200)
AttributeError: module 'random' has no attribute 'randint'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:58:59