# Python 生成隨機數
> 原文: [https://thepythonguru.com/python-generating-random-numbers/](https://thepythonguru.com/python-generating-random-numbers/)
* * *
于 2020 年 1 月 7 日更新
* * *
Python `random`模塊包含生成隨機數的函數。 因此,首先需要使用以下行導入`random`模塊。
```py
import random
```
## `random()`函數
* * *
`random()`函數返回隨機數`r`,使得`0 <= r < 1.0`。
```py
>>> import random
>>> for i in range(0, 10):
... print(random.random())
...
```
**預期輸出**:
```py
0.9240468209780505
0.14200320177446257
0.8647635207997064
0.23926674191769448
0.4436673317102027
0.09211695432442013
0.2512541244937194
0.7279402864974873
0.3864708801092763
0.08450122561765672
```
`randint(a, b)`生成`a`和`b`(含)之間的隨機數。
```py
>>> import random
>>> for i in range(0, 10):
... print(random.randint(1, 10))
...
8
3
4
7
1
5
3
7
3
3
```
下一章將介紹 python 中的[文件處理技術](/python-file-handling/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象