random Module in Python

random Module in Python

This module is very useful in programming. Let’s see all functions:

>>> dir(random)
[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘System
Random’, ‘TWOPI’, ‘_BuiltinMethodType’, ‘_MethodType’, ‘_Sequence’, ‘_Set’, ‘__a
ll__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__initializing__’,
‘__loader__’, ‘__name__’, ‘__package__’, ‘_acos’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’,
 ‘_inst’, ‘_log’, ‘_pi’, ‘_random’, ‘_sha512’, ‘_sin’, ‘_sqrt’, ‘_test’, ‘_test_
generator’, ‘_urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘expovariate’, ‘gammav
ariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’,
‘paretovariate’, ‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’,
 ‘shuffle’, ‘triangular’, ‘uniform’, ‘vonmisesvariate’, ‘weibullvariate’]
>>>

>>> random.randint(3,9)
6
>>> random.randint(1223,888822)
793572
>>> random.randint(4,1)
Traceback (most recent call last):
  File “<stdin>”, line 1, in <module>
  File “D:\Python33\lib\random.py”, line 214, in randint
    return self.randrange(a, b+1)
  File “D:\Python33\lib\random.py”, line 192, in randrange
    raise ValueError(“empty range for randrange() (%d,%d, %d)” % (istart, istop,
 width))
ValueError: empty range for randrange() (4,2, -2)
>>>

The first value must be less than the second. If not, we’ll get the error.

>>> random.random()
0.287274357115488
>>> random.random() * 1000
59.39047817153353
>>> random.random(2,8) * 1000
Traceback (most recent call last):
  File “<stdin>”, line 1, in <module>
TypeError: random() takes no arguments (2 given)
>>>

This function takes no parameters.

>>> e = (‘a’, ‘b’, ‘c’, ‘d’)
>>> e
(‘a’, ‘b’, ‘c’, ‘d’)
>>> random.choice(e)
‘d’
>>> random.choice(e)
‘b’
>>> random.choice(e)
‘b’
>>> random.choice(e)
‘b’
>>> random.choice(e)
‘b’
>>> random.choice(e)
‘b’
>>> random.choice(e)
‘d’
>>> random.choice(e)
‘c’
>>>

We can choice from the items in a sequence.

>>> f = [1,2,3,4,5]
>>> random.shuffle(f)
>>> print(f)
[1, 4, 3, 5, 2]
>>> random.shuffle(f)
>>> print(f)
[5, 1, 4, 3, 2]
>>> random.shuffle(f)
>>> print(f)
[1, 4, 5, 3, 2]
>>>

It must be a mutable sequence like a list, not a tuple.

>>> random.randrange(5, 50, 10)
15
>>> random.randrange(0, 5, 2)
4
>>> random.randrange(0, 100, 25)
50
>>>

Leave a comment