The random module in Python, the magical world of randomness

Get more information

Personal website: Brother Tao talks about Python

Randomness plays a crucial role in computer programming and data science. The random module in Python provides a wealth of tools and functions to help us generate random numbers, operate random sequences, and simulate random events.

In this article, we will share the random module, understand its basic usage, functions and application areas, and provide sample code to help you better understand the magical world of randomness.

Introduction to the random module

The random module in Python is a pseudo-random number generator toolkit that can generate random numbers, perform random sequence operations, and simulate random events. Although the generated numbers are actually pseudo-random, they are random enough for most applications.

Here are some common uses of the random module:

  • Generate random numbers: including integers, floating point numbers and random seeds.

  • Operation sequence: random shuffling, selecting random elements, etc.

  • Simulate random events: simulate coin toss, dice toss, sampling, etc.

Let’s start with basic random number generation and gradually gain a deeper understanding of the functions and usage of the random module.

Random number generation

Generate random integers

To generate a random integer within a specified range, you can use the random.randint() function.

Here is an example that generates a random integer between 1 and 10:

import random

random_integer = random.randint(1, 10)
print(random_integer) #Output: a random integer between 1 and 10

Generate random floating point numbers

To generate random floating point numbers, you can use the random.uniform() function. Here is an example that generates a random floating point number between 0 and 1:

import random

random_float = random.uniform(0, 1)
print(random_float) #Output: a random floating point number between 0 and 1

Generate random seeds

Generate a repeatable sequence of random numbers. To achieve this, you can use the random.seed() function, passing it a fixed seed. This way, the same seed will generate the same sequence of random numbers. Here is an example:

import random

random.seed(42) # Use seed 42
random_number_1 = random.randint(1, 100)
random_number_2 = random.randint(1, 100)

print(random_number_1) #Output: a random integer
print(random_number_2) #Output: a random integer different from the above

Random sequence operation

The random module also provides functions for manipulating random sequences, such as random shuffling and random selection.

Shuffle randomly

To randomly shuffle the elements in a list, you can use the random.shuffle() function.

Here is an example:

import random

my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)

print(my_list) # Output: a randomly ordered list

Randomly select elements

If you need to randomly select one or more elements from a list, you can use the random.choice() function.

Here is an example:

import random

my_list = [1, 2, 3, 4, 5]
random_element = random.choice(my_list)

print(random_element) #Output: a randomly selected element

Simulate random events

The random module can also be used to simulate random events such as coin tosses, dice tosses, and sampling.

Simulating a coin toss

To simulate a coin toss, you can use the random.choice() function to randomly choose one of two possible options.

Here is an example:

import random

coin = ['head', 'tail']
result = random.choice(coin)

print(f"Coin toss result: {<!-- -->result}")

Simulating dice rolling

To simulate a dice roll, you can use the random.randint() function to generate a random integer between 1 and 6.

Here is an example:

import random

dice_roll = random.randint(1, 6)

print(f"Dice rolling result: {<!-- -->dice_roll}")

Simulation sampling

Random sampling is a common task in data science and statistics. You can use the random.sample() function to randomly sample from a list.

Here is an example:

import random

my_population = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sample = random.sample(my_population, 5)

print(f"Random sampling results: {<!-- -->sample}")

Advanced usage

In addition to the above basic functions, the random module also provides more advanced randomness operations. Use random.gauss() to generate random numbers following a Gaussian distribution, use random.choices() to make weighted random choices, and use random. getstate() and random.setstate() to save and restore the generator’s state.

Application fields

Randomness has applications in many fields, including:

  1. Simulation and Modeling: Use randomness in simulation games, financial models, physics simulations, and simulations.

  2. Cryptography: Use pseudo-random number generation in generating encryption keys and hash functions.

  3. Machine Learning: Introducing randomness into data augmentation, initializing neural network weights, and cross-validation.

  4. Statistics: Use randomness in random sampling, Monte Carlo methods, and confidence interval estimation.

  5. Game Development: Create random maps, random enemy spawns, and random events.

  6. Experimental design: In psychological, biological, and medical research, the randomization of experimental and control groups.

Example code

The following is a sample code that demonstrates how to use the random module to generate a simple simulated gambling game:

import random

def roll_dice():
    return random.randint(1, 6)

def play_game():
    money = 100
    while money > 0:
        input("Press Enter to start rolling the dice...")
        dice = roll_dice()
        print(f"{<!-- -->dice} points were thrown")
        if dice == 6:
            money + = 5
            print(f"Won $5, now have ${<!-- -->money}")
        else:
            money -= 2
            print(f"Lost $2, now have ${<!-- -->money}")
    print("You are bankrupt!")

play_game()
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

This example simulates a simple craps gambling game. Each time the player rolls the dice, if the number is 6, he or she wins $5, otherwise he loses $2, until the money is exhausted.

Conclusion

The random module is a very powerful and useful tool in Python, used to generate random numbers, operate random sequences, and simulate random events. It is widely used in fields such as simulation, cryptography, machine learning, statistics, game development and experimental design. By using the random module, you can increase the randomness and predictability of your program to better cope with uncertainty.

Python learning route

Get more information

Personal website: Brother Tao talks about Python

If you want to get more and richer information, you can click on the business card below the article and reply [High-quality information] to get a comprehensive learning information package.


Click on the link card below the article and reply [Quality Information] to directly receive the information gift package.