Latest web development tutorials

Python 隨機數生成

Document 對象參考手冊 Python3實例

以下實例演示瞭如何生成一個隨機數:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.w3big.com

# 生成 0 ~ 9 之间的随机数

# 导入 random(随机数) 模块
import random

print(random.randint(0,9))

執行以上代碼輸出結果為:

4

以上實例我們使用了random 模塊的randint() 函數來生成隨機數,你每次執行後都返回不同的數字(0 到9),該函數的語法為:

random.randint(a,b)

函數返回數字N ,N 為a 到b 之間的數字(a <= N <= b),包含a 和b。

Document 對象參考手冊 Python3實例