We have mentioned the random module many times before. In this section, we will introduce the usage of the random module in detail. The random module mainly provides us with some functions for generating random numbers . The following table summarizes several commonly used functions in the random module.
Generate a random floating point number from 0 to 1, see the following example:
importrandoma=random.random()b=random.random()c=random.random()print(a)print(b)print(c)
The output is:
0.7879655602680620.205244861798563160.8732074424182436
We can see that the value and number of digits of the returned floating point number are not necessarily the same.
I need to pay attention to the difference between randint and randrange. Randint contains a and b, while randint, which will be mentioned later, does not contain a and b.
We can test to see if upper and lower limits are included. The code is as follows:
importrandoma=random.randint(1,3)b=random.randint(1,3)c=random.randint(1,3)print(a)print(b)print(c)
The output is:
312
We can see that it contains the values of a and b.
We mainly use testing to see whether this method contains the values of a and b. Look at the following code:
importrandoma=random.randrange(1,3)b=random.randrange(1,3)c=random.randrange(1,3)d=random.randrange(1,3)print(a)print(b)print( c)print(d)
The output is:
2212
From the test results, we can see that only 1 and 2 do not include the lower bound 3. You can also try to run it yourself.
We used the random.shuffle(x) function in Section 2. It can reorder a sequence, but it should be noted that it only works on changeable sequences, so it is often used to shuffle the elements in the list. .
importrandoma=['d','o','t','c','p','p']print('List before shuffle:',a)random.shuffle(a)print('shuffle The messed up list: ',a)
The output is:
List before shuffling: ['d','o','t','c','p','p'] List after shuffling: ['c','d','p', 'p','t','o']
random.choice(x) can return a random element in a sequence. It is used as follows:
importrandoma=['d','o','t','c','p','p']b='dotcpp'c=('d','o','t','c' ,'p','p')print(random.choice(a))print(random.choice(b))print(random.choice(c))
The output is:
odp
Used to generate random floating point numbers within a specified range, the code is as follows:
importrandoma=random.uniform(1.1,3.3)b=random.uniform(5,6)c=random.uniform(100,200)print(a)print(b)print(c)
The output is:
2.58026565795090875.977193880181603141.03779834775494
That’s all about the functions of the random module. The above six usages include common methods for generating random numbers. If you want to use more methods in the random module, you can learn more in the Python help documentation.