目錄
零基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
Python random 模塊包括返回隨機數的函數,可以用於模擬或者任何產生隨機輸出的程序。
一.Python random 模塊常用函數介紹
-
random.random() — 生成一個從 0.0(包含)到 1.0(不包含)之間的隨機浮點數;
-
random.uniform(a, b) — 生成一個範圍爲 a≤N≤b 的隨機數,隨機數類型是浮點數;
-
random.randint(a, b) — 生成一個範圍爲 a≤N≤b 的隨機數,隨機數的類型是整形,注意與 random.uniform(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 模塊
本文由博客 - 猿說編程 猿說編程 發佈!