random模块常用方法
1)random.random()
import random
random.random()
0.07391371910358258
2)random.uniform(a,b)
import random
print(random.uniform(10,20))
print(random.uniform(20,10))
10.897982983785754
14.111023929383776
3)random.randint(a,b)
import random
print(random.randint(12,20))
print(random.randint(20,20))
19
20
4)random.randrange([start],stop[,step])
5)random.choice()
import random
print(random.choice('学习python'))
print(random.choice(['good','hello','is','hi','boy']))
print(random.choice(('str','tuple','list')))
学
boy
str
6)random.shuffle(x[,random])
p=['hehe','xixi','heihei','haha','zhizhi','lala','momo..da']
random.shuffle(p)
print(p)
['hehe', 'zhizhi', 'momo..da', 'haha', 'heihei', 'lala', 'xixi']
7)random.sample(sequence,k)
list1=[1,2,3,4,5,6,7,8,9,10]
slice=random.sample(list1,5)
print(slice)
print(list1)
[5, 2, 8, 4, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
使用举例
import random
random.choice('abcdefg')
'b'
import random
random.sample('abcdefghijk',3)
['k', 'i', 'h']
import random
" ".join(random.sample(['a','b','c','d','e','f','g','h'],3)).replace(" ","")
'bea'
import random
random.choice(['haha','hehe','heihei','acm','xixi'])
'heihei'
import random
items=[1,2,3,4,5,6,7]
random.shuffle(items)
items
[6, 5, 4, 3, 1, 2, 7]
import random
random.randrange(0,101,2)
96
random.uniform(1,100)
61.7888094316059
序列随机数应用:猜单词游戏
import random
WORDS=('python','jumble','easy','difficult','answer','continue','phone','position','game','student')
print('---欢迎参加猜单词游戏---')
print('-请把字母组合成一个正确的单词-\n')
flag='y'
while flag=='y' or flag=='Y':
word=random.choice(WORDS)
c=word
jumble=""
while word:
position = random.randrange(len(word))
jumble+=word[position]
word=word[:position]+word[position+1:]
print('乱序后的单词:',jumble)
w=input('\n请你猜: ')
while w!=c and w!='':
print('回答错误')
w=input('请继续猜')
print('回答正确!')
flag=input('\n是否继续(Y/N):')
---欢迎参加猜单词游戏---
-请把字母组合成一个正确的单词-
乱序后的单词: yeas
请你猜: easy
回答正确!
是否继续(Y/N):y
乱序后的单词: amge
请你猜: amge
回答错误
请继续猜game
回答正确!
是否继续(Y/N):n