Home>Article>Backend Development> How to generate random numbers in python
Use the random module in python to generate random numbers.
Several usages of the random module are as follows
1. Random floating point numbers
random() --- Produce numbers greater than or equal to 0 and less than 1 Floating point number
ret = random.random() print(ret)
uniform(a,b) --- Generate a random floating point number in the specified range
ret = random.uniform(1, 4) print(ret)
2. Random integer
randint(a,b) --- 产生a,b范围内的整数,包含开头和结尾
randrange(start, stop,[step]) --- Generate an integer within the range of start and stop, including the beginning but not the end. step specifies the step size for generating random numbers.
ret = random.randrange(1, 6, 2) print(ret)
3. Randomly select a data
random.choice(lst) --- Randomly return a data in the sequence
lst = ['a', 'b', 'c'] ret = random.choice(lst) print(ret)
4.Disrupt
shuffle() --- Shuffle the order of the list
lst = ['a', 'b', 'c'] print(lst) # ['a', 'b', 'c'] random.shuffle(lst) print(lst) # ['b', 'a', 'c']
The above is the detailed content of How to generate random numbers in python. For more information, please follow other related articles on the PHP Chinese website!