Python random 模組 - Python零基礎入門教程
阿新 • • 發佈:2021-06-18
目錄
零基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
Python random 模組包括返回隨機數的函式,可以用於模擬或者任何產生隨機輸出的程式。
一.Python random 模組常用函式介紹
-
random.random() — 生成一個從 0.0(包含)到 1.0(不包含)之間的隨機浮點數;
-
random.uniform(a, b) — 生成一個範圍為 a≤N≤b 的隨機數,隨機數型別是浮點數;
-
random.randint(a, b)
-
random.sample(seq, k) — 從 seq 序列中隨機抽取 k 個獨立的元素;
-
random.choice(seq) — 從 seq 序列中隨機抽取一個元素,如果 seq 為空,則引發 IndexError 異常;
-
random.randrange(start, stop, step) — 返回從 start 開始到 stop 結束、步長為 step 的隨機數(可以用該方法返回隨機偶數或者奇數),示例:
返回 0 到 100 的隨機偶數
random.randrange(0, 101 , 2)
返回 0 到 100 的隨機奇數
random.randrange(1, 101 , 2)
二.Python random 模組使用
Python random 使用案例如下:
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:猿說程式設計 @Blog(個人部落格地址): www.codersrc.com @File:Python random 模組.py @Time:2021/3/29 07:37 @Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累! """ import random #生成範圍為0.0≤x<1.0 的偽隨機浮點數 print (random.random()) #生成範圍為2≤x<10 的偽隨機浮點數 print (random.uniform(2, 10)) #生成從0 到9 的偽隨機整數 print(random.randrange(10)) #生成從0 到100 的隨機偶數 print (random.randrange(0, 101 , 2)) #隨機抽取一個元素 print (random.choice (['何以解憂','猿說python','python教程'])) #隨機抽取2 個獨立的元素 print (random.sample([10, False , 30 , "hello" , 50], k=2)) ''' 輸出結果 0.9662431302672254 8.850312880563921 0 46 猿說python [30, 'hello'] '''
三.猜你喜歡
- Python 配置環境
- Python 變數
- Python 運算子
- Python 條件判斷 if/else
- Python while 迴圈
- Python break
- Python continue
- Python for 迴圈
- Python 字串
- Python 列表 list
- Python 元組 tuple
- Python 字典 dict
- Python 條件推導式
- Python 列表推導式
- Python 字典推導式
未經允許不得轉載:猿說程式設計 » Python random 模組
本文由部落格 - 猿說程式設計 猿說程式設計 釋出!