Home > Backend Development > Python Tutorial > How to generate random numbers in python

How to generate random numbers in python

silencement
Release: 2019-06-17 13:22:58
Original
28083 people have browsed it

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)
Copy after login

uniform(a,b) --- Generate a random floating point number in the specified range

ret = random.uniform(1, 4)
print(ret)
Copy after login

2. Random integer

randint(a,b) --- 产生a,b范围内的整数,包含开头和结尾
Copy after login

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)
Copy after login

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)
Copy after login

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']
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template