數字
數字數據類型用于存儲數值,比如整數、小數等。數據類型是不允許改變的,這就意味著如果改變數字數據類型的值,將重新分配內存空間。
創建數字類型的變量:
var1 = 1
var2 = 10
創建完變量后,如果想廢棄掉這個變量(比如后面不再使用),可以使用 del 關鍵字刪除這個變量:
del var1
del var1,var2
:::warning
需要注意的是,del 刪除的是名稱的綁定,而不是對象本身。 如果沒有任何其他名稱引用該對象,那么該對象最終會被 Python 的垃圾回收機制回收,釋放其占用的內存
:::
數字類型的變量可以通過之前講過的運算符對其進行操作:
var1 = 1
var2 = 2var3 = 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)