Random function details of Python built in functions

  • 2021-12-12 09:02:20
  • OfStack

Directory

Import module:


import random

1. random. choice (list/tuple/string), randomly select one element in the list or tuple, and randomly select one character if it is a string


num1 = random.choice(['hello',True,1,[1,4,5]])
print(num1)


Output (the result of each output is not 1 fixed and 1 sample):

1

2. random. randrange ([start, end), step): Returns 1 random number from [start, end) with step size step

If start is not written, it defaults to 0 Multiple step is not written, and the default is 1 But end1 must have num2 =

random.randrange(100)
print(num2)#  Head and tail 
num3 = random.randrange(80,100,2)
print(num3)#  Take 1 A 1~6 Random number of 
print(random.randrange(1,7))

Output (the result of each output is not 1 fixed and 1 sample):
83
84
6

3. random. random (): Returns a random number [0, 1], and the result is a floating point number


'''
 No one answers the problems encountered in study? Xiaobian created 1 A Python Learning and communication group: 531509025
 Looking for like-minded friends and helping each other , There are also good video learning tutorials and PDF E-books! 
'''
num4 = random.random()
print(num4)


Output (the result of each output is not 1 fixed and 1 sample):
0.8073295394931393

4. random. shuffle (list): Randomly sort all the elements in the sequence, and directly operate the sequence "sequence changes" without returning a value


list1 = [1,2,3,5,6,7]
random.shuffle(list1)
print(random.shuffle(list1)) #  The result returned is None
print(list1)


Output (the result of each output is not 1 fixed and 1 sample):
None
[1, 7, 5, 6, 3, 2]

5. random. uniform (m, n): Randomly generate a floating point number [m, n]


print(random.uniform(5,4))


Output (the result of each output is not 1 fixed and 1 sample):
4.697767338612918

6. random. randint (m, n)

Randomly generate an integer of [m, n]


print(random.randint(-1,4))


Output (the result of each output is not 1 fixed and 1 sample):
0


Related articles: