random.randint error

2020-08-09 06:40发布

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 queries in IDLE. How can I fix this?

6条回答
干净又极端
2楼-- · 2020-08-09 07:08

Change your file name from random.py to any thing else like random_number.py that resolve your issue.

查看更多
我命由我不由天
3楼-- · 2020-08-09 07:14

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

查看更多
4楼-- · 2020-08-09 07:21

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.

查看更多
家丑人穷心不美
5楼-- · 2020-08-09 07:21

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, "= "
查看更多
一夜七次
6楼-- · 2020-08-09 07:24

Check your files name! In your case “random” is key word, you can not use "random" as a file name. Take care that no files are named random.py.

查看更多
Emotional °昔
7楼-- · 2020-08-09 07:25

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

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

查看更多
登录 后发表回答