11.14. Random Module#

import random

11.14.1. To check the available methods in this module#

print(dir(random))
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
print(random.random())
0.4129434337112411
  • By default,it gives random number between 0 and 1It gives numbers between 0 and 1

    • 0 is inclusive

    • 1 is exclusive

11.14.1.1. Summary#

  • Get random number(float) between 0 and 1 (1 being exclusive) - random.random()

  • Get random number(float) between custom range - random.uniform(min,max)

  • Get random integer between a range - random.randint(min,max) random.choice(list)

for i in range(10):
    print(random.random())
0.2277179807124028
0.9356877918536378
0.4118147944277468
0.1525578815967028
0.6298771193949251
0.7153119919539381
0.5289345390164477
0.17960255407669634
0.9829411541623907
0.02956770132247477

11.14.2. Get random numbers between custom range#

  • Use uniform()

# get random numbers from 3 to 7
print(random.uniform(3,7))
3.341676225451783
print(random.randint(1,6))
6
outcomes=['rock','paper','scissor']
for i in range(5):
    print(random.choice(outcomes))
rock
rock
paper
rock
scissor