Python random module

Python random module contains various functions include random number and string generation etc. Generate a random number between 0 and 1:

>>> import random
>>> x = random.random()
>>> x
0.7357546623541338
Generate a random integer in a range:
>>> x = random.randint(1,13) #random integer between 1 and 13
>>> x
7
Random float number in a range:
>>> random.uniform(3,5) #float number 3 < x < 5
>>> random.uniform(5,3) #float number 3 < x < 5
4.5798298023
random.randrange([start],stop[,step]): get a random element from range(start,stop,step)
>>> random.randrange(3,30,4) #pick one from [3,7,11,15,19,23,27]
27
>>> random.randrange(1,8,2) #pick one from [1,3,5,7]
3
>>> random.randrange(1,8,2) #pick one from [1,3,5,7]
7
Random pick from a sequence:
>>> random.choice('abcde')
'e'
>>> random.choice('abcde')
'b'
Random pick an fragment from a sequence:
>>> random.sample('abcde',2)
'bc'
>>> random.sample('abcde',2)
'de'










endmemo.com © 2024  | Terms of Use | Privacy | Home