Python random module tutorial
In Python, the random module is used to generate random numbers. Various functions within this module can be used to create random numbers, as shown below:
- 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)
- Generate a random element in a random sequence.
import random
# 从指定的序列中随机选择一个元素
my_list = ['apple', 'banana', 'cherry', 'date']
random_element = random.choice(my_list)
print(random_element)
- Shuffle the elements in a sequence.
import random
# 打乱一个序列中的元素顺序
my_list = ['apple', 'banana', 'cherry', 'date']
random.shuffle(my_list)
print(my_list)
These are some common functions in the random module that can be used to generate random numbers or manipulate elements in a sequence as needed.