Random Module in Python

The random module must be imported. This module provides an array of tools, for tasks such as picking a random floating-point number between 0 and 1, selecting a random integer between two numbers, choose an item at random from a sequence, shuffle a list of items randomly, etc:

>>> import random
>>>
>>> # Random floats between 0 and 1
>>> random.random()
0.9204964667286465
>>> random.random()
0.20793591629861263
>>>
>>> # Random numbers between 1 and 10
>>> random.randint(1, 10)
5
>>> random.randint(1, 10)
7
>>> # Random choice
>>> random.choice(['Python', 'Ruby', 'Java', 'JavaScript'])
'Ruby'
>>>
>>> # Random shuffle
>>> lang_prog = ['Python', 'Ruby', 'Java', 'JavaScript']
>>> random.shuffle(lang_prog)
>>> lang_prog
['Python', 'Ruby', 'JavaScript', 'Java']
>>> random.shuffle(lang_prog)
>>> lang_prog
['Java', 'Python', 'JavaScript', 'Ruby']

Leave a Reply