Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python random function

I'm having problems with Python's import random function. It seems that import random and from random import random are importing different things. I am currently using Python 2.7.3

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> random()

Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
    random()
NameError: name 'random' is not defined
>>> random.randint(1,5)

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
random.randint(1,5)
NameError: name 'random' is not defined
>>> import random
>>> random()

Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
random()

TypeError: 'module' object is not callable
>>> random.randint(1,5)
2
>>> from random import random
>>> random()
0.28242411635200193
>>> random.randint(1,5)

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
random.randint(1,5)
AttributeError: 'builtin_function_or_method' object has no attribute 'randint'
>>> 
like image 339
donsavage Avatar asked Feb 20 '13 17:02

donsavage


People also ask

What is random () function in Python?

Python Random random() Method The random() method returns a random floating number between 0 and 1.


2 Answers

import random imports the random module, which contains a variety of things to do with random number generation. Among these is the random() function, which generates random numbers between 0 and 1.

Doing the import this way this requires you to use the syntax random.random().

The random function can also be imported from the module separately:

from random import random

This allows you to then just call random() directly.

like image 148
jam Avatar answered Sep 20 '22 08:09

jam


The random module contains a function named random(), so you need to be aware of whether you have imported the module into your namespace, or imported functions from the module.

import random will import the random module whereas from random import random will specifically import the random function from the module.

So you will be able to do one of the following:

import random
a = random.random()
b = random.randint(1, 5)
# you can call any function from the random module using random.<function>

or...

from random import random, randint   # add any other functions you need here
a = random()
b = randint(1, 5)
# those function names from the import statement are added to your namespace
like image 35
Andrew Clark Avatar answered Sep 20 '22 08:09

Andrew Clark