28

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?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
foobar
  • 297
  • 1
  • 3
  • 3

8 Answers8

84

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
7

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Sebastien
  • 1,057
  • 8
  • 7
  • May I know what is the reason behind this? does python checks the filename during execution? – smc Oct 06 '19 at 10:50
7

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
behnaz.sheikhi
  • 624
  • 8
  • 6
5

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

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Vivekanand Panda
  • 832
  • 12
  • 23
3

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
toc777
  • 2,607
  • 2
  • 26
  • 37
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.

-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, "= "
Amin Khodamoradi
  • 392
  • 1
  • 6
  • 18
-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

Kashif
  • 1,364
  • 17
  • 21