数字
数字数据类型用于存储数值,比如整数、小数等。数据类型是不允许改变的,这就意味着如果改变数字数据类型的值,将重新分配内存空间。
创建数字类型的变量:
var1 = 1
var2 = 10
创建完变量后,如果想废弃掉这个变量(比如后面不再使用),可以使用 del 关键字删除这个变量:
del var1
del var1,var2
:::warning
需要注意的是,del 删除的是名称的绑定,而不是对象本身。 如果没有任何其他名称引用该对象,那么该对象最终会被 Python 的垃圾回收机制回收,释放其占用的内存
:::
数字类型的变量可以通过之前讲过的运算符对其进行操作:
var1 = 1
var2 = 2
var3 = var1 + var2
随机数
Python 中的 random 类中提供了常用的关于生成随机数或挑选随机的一个值的相关的方法。
函数 | 描述 |
---|---|
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">choice(seq)</font> |
从序列的元素中随机挑选一个元素。例如:<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">random.choice(range(10))</font> ,从 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">0</font> 到 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">9</font> 中随机挑选一个整数 |
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">randrange([start,] stop [,step])</font> |
从指定范围内,按指定基数递增的集合中获取一个随机数。基数默认值为 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">1</font> |
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">random()</font> |
随机生成下一个实数,范围在 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">[0, 1)</font> 内 |
randint(a,b) |
随机生成指定范围内的一个整数,范围在 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">[a, b]</font> 内,这里是左闭右闭 |
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">seed([x])</font> |
改变随机数生成器的种子 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">seed</font> 。如果不了解原理,通常不需要特别设定,Python 会自动选择 |
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">shuffle(lst)</font> |
将序列的所有元素随机排序 |
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">uniform(x, y)</font> |
随机生成下一个实数,范围在 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">[x, y]</font> 内 |
:::warning
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">random()</font>
的范围是左闭右开区间 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">[0, 1)</font>
,而 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">uniform(x, y)</font>
是 闭区间 <font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">[x, y]</font>
<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">shuffle(lst)</font>
会直接修改原列表,而非返回一个新列表
:::
比如生成一个随机的在 1 到 10 之间的整数:
import random
random_num = random.randint(1, 10) # 生成 1~10 之间的随机整数(包括 1 和 10)
print(random_num)