Article From:https://www.cnblogs.com/anningwang/p/9062774.html

If you do not understand the relationship between generating random numbers in Python and the most commonly used functions in the random module, the following article is the relationship between the Python generated random numbers and the most commonly used functions in the random module, hoping that you will gain something. Here is the articleThe introduction of the chapter.

random.random()It is used to generate a random number of points within a specified range. One of the two parameters is the upper limit and the other is the lower limit. If a > B, then a random number is generated

n Value: a < = n < = B. If a < B, then B < = n < = a.  

print random.uniform(10, 20) 
print random.uniform(20, 10) 

It is used to generate an integer within a specified range. The parameter a is the lower limit, the parameter B is the upper limit, and Python generates the random number.

print random.randint(12, 20) #The generated random number n: 12 < = n < = 20The result of print random.randint (20, 20) is always 20#print random.randint (20, 10)The statement is wrong.

The lower limit must be less than the upper limit.


From the specified range, according to the set of incremental base sets, this article is a partial introduction to the application of Python to generate random numbers.

Random integer:

import random


Random selection of 0 to 100 of the even numbers:

import random
random.randrange(0, 101, 2)


Random floating-point number:

import random


random.uniform(1, 10)


Random characters:

import random


A specific number of characters are selected in multiple characters:

import random

[‘a’, ‘d’, ‘b’]

a = range(1000)

[394, 111, 89, 413, 402]

Select a specific number of characters in multiple characters to form a new string:

import random
import string
string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).replace(" ","")


Random selection of strings:

import random
random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )


Shuffle the cards:

import random
items = [1, 2, 3, 4, 5, 6]
print items

[3, 2, 5, 6, 4, 1]

Link of this Article: Python random usage method

Leave a Reply

Your email address will not be published. Required fields are marked *