1. 程式人生 > >Python-隨機模塊-random

Python-隨機模塊-random

star abcdefg 模塊 abcd IV AC operator sample pre

random

  生成隨機變量

生成 [0, 1) 隨機數            .random

import random

random_number = random.random()
print(random_number)
print(random_number + 1)

生成[start, end] 隨機數          .uniform

import random

random_number = random.uniform(0, 10)
print(random_number)

生成 [start, end] 區間隨機整數       .randint

import random

random_number = random.randint(1, 10)
print(random_number)

生成 (start, end) 區間隨機整數       randrange

import random

random_number = random.randrange(1, 10)
print(random_number)

從序列中隨機取一個值           choice

import random

random_sequence = random.choice(["1", "2", "3"])
print(random_sequence)

從序列中隨機取樣             sample

import random

target_str = "0123456789abcdefghijklmnopqrstuvwxyz"

random_sequence = random.sample(target_str, 6)
print(random_sequence)
# 6位數隨機驗證碼
print(‘‘.join(random_sequence))

算數運算驗證碼實現

import random

number_str = "123456789"
letter_str = ‘abcdefghijklmnopqrstuvwxyz‘
operator = "+-×"
random_str = random.choice(number_str) + random.choice(operator) +              random.choice(number_str) + random.choice(operator) +              random.choice(number_str)
print(random_str.replace(‘ב, ‘*‘))
print(eval(random_str.replace(‘ב, ‘*‘)))

Python-隨機模塊-random