random module in Python3

The random module in Python is used to generate random numbers.

The following describes the functions of the random module in detail:

1.random.random()

 # used to generate a 0 to 1

Random float: 0 <= n < 1.0

1 import random  
2 a = random.random()
3 print (a)  

 

2.random.uniform(a,b) 

#Used to generate a random number of symbols within a specified range, one of the two parameters is the upper limit and the other is the lower limit. If a > b, the generated random number n: a <= n <= b. If a < b, then b <= n <= a.

1 import random  
2 print(random.uniform(1,10))  
3 print(random.uniform(10,1)) 

 

 

3.random.randint(a, b)

 #Used to generate an integer in the specified range. Where parameter a is the lower limit, parameter b is the upper limit, the generated random number n: a <= n <= b

1 import random  
2 print(random.randint(1,10))  

 


4.random.randrange ([start], stop [, step])

 #Get a random number from the set incremented by the specified base within the specified range.

random.randrange(10, 30, 2), the result is equivalent to getting a random number from the sequence [10, 12, 14, 16, ... 26, 28].

random.randrange(10, 30, 2) is equivalent in result to random.choice(range(10, 30, 2).

1  import random  
 2  print (random.randrange (10,30,2)) 

 

5.random.choice(sequence)

# random.choice gets a random element from the sequence. Its function prototype is: random.choice(sequence).

The parameter sequence represents an ordered type. Here to explain: sequence is not a specific type in python, but refers to a series of types. list, tuple, and string all belong to sequence.

1 import random  
2 lst = ['python','C','C++','javascript']  
3 str1 = ('I love python')  
4 print(random.choice(lst))
5 print(random.choice(str1))  

 

6.random.shuffle(x[, random])

#Used to shuffle the elements in a list, that is to randomly arrange the elements in the list.

1 import random
2 p = ['A' , 'B', 'C', 'D', 'E' ]
3 random.shuffle(p)  
4 print (p)  

 

7.random.sample(sequence, k)

#从指定序列中随机获取指定长度的片断并随机排列。注意:sample函数不会修改原有序列。

1 import random   
2 lst = [1,2,3,4,5]  
3 print(random.sample(lst,4))  
4 print(lst) 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324738096&siteId=291194637