Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random in python 2.5 not working?

Tags:

python

I am trying to use the import random statement in python, but it doesn't appear to have any methods in it to use.

Am I missing something?

like image 896
user13050 Avatar asked Sep 16 '08 16:09

user13050


4 Answers

You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my_random.py and/or remove the random.pyc file.

To tell for sure what's going on, do this:

>>> import random
>>> print random.__file__

That will show you exactly which file is being imported.

like image 97
Jerry Hill Avatar answered Sep 28 '22 07:09

Jerry Hill


This is happening because you have a random.py file in the python search path, most likely the current directory.

Python is searching for modules using sys.path, which normally includes the current directory before the standard site-packages, which contains the expected random.py.

This is expected to be fixed in Python 3.0, so that you can't import modules from the current directory without using a special import syntax.

Just remove the random.py + random.pyc in the directory you're running python from and it'll work fine.

like image 42
Johan Dahlin Avatar answered Sep 28 '22 05:09

Johan Dahlin


I think you need to give some more information. It's not really possible to answer why it's not working based on the information in the question. The basic documentation for random is at: https://docs.python.org/library/random.html

You might check there.

like image 22
jamuraa Avatar answered Sep 28 '22 05:09

jamuraa


Python 2.5.2 (r252:60911, Jun 16 2008, 18:27:58)
[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> random.seed()
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> random.randint(0,3)
3
>>> random.randint(0,3)
1
>>>  
like image 29
Vinko Vrsalovic Avatar answered Sep 28 '22 06:09

Vinko Vrsalovic