python's random library provides functions for generating random numbers, which can be used for operations such as generating random numbers and random selection. Here are some common ways to use it:
import random # 生成一个0到9之间的随机整数 random_number = random.randint(0, 9)
import random # 生成一个0到1之间的随机小数 random_float = random.random()
import random # 生成一个1到100之间的随机数 random_number = random.randrange(1, 101) # 从指定的列表中随机选择一个元素 random_element = random.choice(["apple", "banana", "orange"])
import random my_list = [1, 2, 3, 4, 5] # 随机打乱列表的顺序 random.shuffle(my_list)
import random import string # 生成一个包含10个随机字母的字符串 random_string = ''.join(random.choices(string.ascii_letters, k=10))
These are just some common usage methods. The random library also provides other functions, such as generating random colors, random dates, etc. For detailed usage, please refer to the official documentation: https://docs.Python.org/3/library/random.html
The above is the detailed content of How to use python random library. For more information, please follow other related articles on the PHP Chinese website!