30

I have some code that looks something like this:

import random

n = 0
while n <= 50:
  n = n+1
  a = random.randint(1, 16)
  b = random.randint(1, 5)
  print n, ". ", a, "-", b, "= "

For some reason, when running it, I get the following error:

AttributeError: 'module' object has no attribute 'randint'.

However, I have no problems when running the same random.randint codes in IDLE.

How can I fix this?

0

8 Answers 8

90

You have another module called "random" somewhere. Did you name your script "random.py"?

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Just wanted to add to this - in my case I had a function named random (What I get for having my partners send me their portion of code, lol)
A very nice resolution to my random.py script, thanks!
Of course I had a script called random.py. :-) - Thanks for this answer!
10

Check your files name!

In your case “random” is a built-in module, so you can not use "random" as a file name. Take care that no files are named random.py.

1 Comment

May I know what is the reason behind this? does python checks the filename during execution?
9

The error is related to the file name.

Probably the name of the python file or another file in your project is random.py. After changing it, there won't be any error.

Comments

6

Change your file name from random.py to anything else like random_number.py to resolve your issue.

Comments

4

The code works fine for me, so you must have another module called "random" on your PYTHONPATH.

Try a dir(random) to see what's in it. This might make it easier to remember why you have another module named random and where it is.

Comments

3

If the filename you are working on or another file in your project is named "random.py", your program tries to find the randint function in that location, and can't find it.

You should change any filenames random.py to something else. After this, "import random" will resolve to the "actual" random.py module and you will successfully use randint or any other function in the module.

Comments

-1

You can easily solve the problem using numpy array , just doing as follows

import numpy as np

n = 0
while n <= 50:
  n = n+1
  a = np.random.randint(1, 16)
  b = np.random.randint(1, 5)
  print n, ". ", a, "-", b, "= "

Comments

-1

AttributeError: 'module' object has no attribute 'randint' same error show me too so that i'm doing mistake import random but my file name also random.py so i change file name to ranom_data.py so it's work simple example share with you

import random
x = random.randint(1,10)
print(x)

so it's work

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.