Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Alex Watts
8,396 PointsI have an issue in python!
Hello,
I have used the random library to generate a random number, however I get an error (see below):
Traceback (most recent call last):
File "numbergame.py", line 7, in <module>
secret_num = random.randint(1, 10)
AttributeError: module 'random' has no attribute 'randint'
This the code I used (see blow):
#Import random library
import random
#Create a random number
secret_num = random.randint(1, 10)
3 Answers
Gianpaul Rachiele
4,844 PointsYou imported the wrong thing. You need to import numpy not random. "random" is a class within the numpy package so you have to import and call it like this:
import numpy
secret_num = numpy.random.randint(1, 10)
if you want to not use the numpy part in the beginning when you are calling the function you can import numpy in one of the following ways:
from numpy import random
secret_num = random.randint(1, 10)
from numpy import *
secret_num = random.randint(1, 10)
The difference between the two above is that the first one imports only the random class of functions where as the second is importing the entire numpy package however you don't need to specify the functions are coming from the numpy package. You should really only use the second way if you don't plan on using any other packages in your script.
Hope this helped!
Alex Watts
8,396 PointsHi Gianpaul,
I have just tried both your methods, but they do not seem to work. I am using workspaces, however when I tried import.random in the python IDLE it worked! I cannot explain this issue.
Thanks for your time and I really appreciate your help! :)
Gianpaul Rachiele
4,844 PointsI probably should have mentioned that you needed to install the numpy package.
Alex Watts
8,396 PointsThat would make sense.