The random module in Python, the magical world of randomness

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:

arduino
Copy code
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:

arduino
Copy code
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:

ini
Copy code
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:

scss
Copy code
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:

ini
Copy code
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:

arduino
Copy code
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:

arduino
Copy code
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:

arduino
Copy code
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:

python
Copy code
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()

This example simulates a simple craps gambling game, where each time the player rolls the dice, they win $5 if the number is 6, otherwise they lose $2, until the money runs out.

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.

Digression

In this rapidly growing technology era, programming is like a ticket to a world of infinite possibilities for many people. Among the star lineup of programming languages, Python is like the dominant superstar. With its concise and easy-to-understand syntax and powerful functions, Python stands out and becomes one of the hottest programming languages in the world.


The rapid rise of Python is extremely beneficial to the entire industry, but “There are many popular people and not many people“, which has led to a lot of criticism, but it still cannot stop its popularity. development momentum.

If you are interested in Python and want to learn Python, here I would like to share with you a Complete set of Python learning materials, which I compiled during my own study. I hope it can help you, let’s work together!

Friends in need can click the link below to get it for free or Scan the QR code below to get it for free

CSDN Gift Package: Free sharing of the most complete “Python learning materials” on the entire network(safe link, click with confidence )

?

1Getting started with zero basics

① Learning route

For students who have never been exposed to Python, we have prepared a detailed Learning and Growth Roadmap for you. It can be said to be the most scientific and systematic learning route. You can follow the above knowledge points to find corresponding learning resources to ensure that you learn more comprehensively.

② Route corresponding learning video

There are also many learning videos suitable for beginners. With these videos, you can easily get started with Python~

③Exercise questions

After each video lesson, there are corresponding exercises to test your learning results haha!

2Domestic and foreign Python books and documents

① Documents and books

3Python toolkit + project source code collection

①Python toolkit

The commonly used development software for learning Python is here! Each one has a detailed installation tutorial to ensure you can install it successfully!

②Python practical case

Optical theory is useless. You must learn to type code along with it and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases. 100+ practical case source codes are waiting for you!

③Python mini game source code

If you feel that the practical cases above are a bit boring, you can try writing your own mini-game in Python to add a little fun to your learning process!

4Python interview questions

After we learn Python, we can go out and find a job if we have the skills! The following interview questions are all from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and Alibaba bosses have given authoritative answers. I believe everyone can find a satisfactory job after reviewing this set of interview materials.

5Python part-time channels

Moreover, after learning Python, you can also take orders and make money on major part-time platforms. I have compiled various part-time channels + part-time precautions + how to communicate with customers into documents.

All the above information , if friends need it, you can scan the QR code below to get it for free
?