深度阅读

how to use the Python random library to generate random numbers

作者
作者
2023年08月22日
更新时间
9.38 分钟
阅读时间
0
阅读量

Sure, here’s an example of how to use the Python random library to generate random numbers:

import random

# Generate a random integer between 1 and 10 (inclusive)
num = random.randint(1, 10)
print(num)

# Generate a random float between 0 and 1
flt = random.random()
print(flt)

# Shuffle a list
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)

In this example, we use the random.randint() method to generate a random integer between 1 and 10 (inclusive), the random.random() method to generate a random float between 0 and 1, and the random.shuffle() method to shuffle a list.

There are many more methods available in the Python random library for generating random numbers and manipulating random values, such as selecting a random item from a list, generating random strings, and more. You can explore the Python documentation to learn more about the random library and its functionalities.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。