前言
我们在编程过程中有时候需要用到随机数,例如模拟掷骰子,模拟抽签等等。Python为我们提供了random
包帮助我们生成随机数。
实践
例如我们要生成1至6之间的随机正整数:
x = random.randint(1, 6)
print(x)
>>> 2
生成0到1之间的小数:
y = random.random()
print(y)
>>> 0.5334639240331638
随机抽取列表中的某个元素:
my_list = ['rock', 'paper', 'scissors']
z = random.choice(my_list)
print(z)
>>> paper
随机打乱一个列表中的所有元素:
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, "J", "Q", "K", "A"]
random.shuffle(cards)
print(cards)
>>> [6, 3, 'A', 4, 9, 'Q', 5, 1, 8, 2, 'J', 'K', 7]
以上便是随机数的全部内容,感谢大家的收藏、点赞、评论。我们下一节将介绍异常(Exception),敬请期待~