Python报错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.pyto something that doesn't clash with Python's standard modules, liketurtle_random_dots.py. - Clean up cached files: If there's a
random.pycfile 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, andrandom.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

