Reading Time: 1 minutes
Generating random elements with the random module in Python
The standard library called random helps the user to inject simulation into your Python programs. Its randint(x, y) function gives a random integer in the range marked by its arguments, inclusive of both end points. If you do not want the upper bound to be inclusive in the range, you can use the randrange(x, b) function, which even offers a step argument just like range().
>>> import random >>> random.randint(0, 5) # random number from 1-5 3 >>> random.randint(0, 5) 5 >>> random.randint(0, 5) 3 >>> random.randrange(0, 5) # random number from 1-4 1 >>> random.randrange(0, 5) 4 >>> random.randrange(0, 5) 0 >>> random.randrange(0, 5, 2) # random number from 1-4 & step = 2 2 >>> random.randrange(0, 5, 2) 0 >>> random.randrange(0, 5, 2) 2 >>> random.randrange(0, 5, 2) 4
To generate random elements other than integers, we have a method called choice(), which accepts an iterable and returns a random element from it.
>>> random.choice( ['a', 'b'] ) 'a' >>> random.choice( ['a', 'b'] ) 'a' >>> random.choice( ['a', 'b'] ) 'b' >>> random.choice( ['a', 'b'] ) 'a' >>> random.choice( ['a', 'b'] ) 'b'