1. 程式人生 > 其它 >Python random 模組 - Python零基礎入門教程

Python random 模組 - Python零基礎入門教程

目錄

零基礎 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']
'''

三.猜你喜歡

  1. Python 配置環境
  2. Python 變數
  3. Python 運算子
  4. Python 條件判斷 if/else
  5. Python while 迴圈
  6. Python break
  7. Python continue
  8. Python for 迴圈
  9. Python 字串
  10. Python 列表 list
  11. Python 元組 tuple
  12. Python 字典 dict
  13. Python 條件推導式
  14. Python 列表推導式
  15. Python 字典推導式

未經允許不得轉載:猿說程式設計 » Python random 模組

本文由部落格 - 猿說程式設計 猿說程式設計 釋出!