Python Random Module: Generate Random Numbers
In Python, you can use the random module to generate random numbers. Here are some common ways to use the random module:
- Generate a random integer.
import random
# 生成一个在指定范围内的随机整数
random_number = random.randint(1, 100)
print(random_number)
- Generate a random floating-point number.
import random
# 生成一个在指定范围内的随机浮点数
random_float = random.uniform(1.0, 10.0)
print(random_float)
- Choose a random element from the list.
import random
# 从列表中随机选择一个元素
my_list = [1, 2, 3, 4, 5]
random_element = random.choice(my_list)
print(random_element)
- Shuffle a list:
import random
# 洗牌一个列表
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
These are just some common functions provided by the random module, you can find many other uses in the official documentation.