模块-random随机数

 random随机数

  • choice#随机选择一个元素
  • sample#从L中随机选择n个元素
  • shuffle#随机重排L中元素
  • randint#从m~n中随机选择一个整数

一、生成随机数random.choice(L),sample(L,n),randint(m,n)

import random
elements=["earth","air","fire","water"]
print(random.choice(elements))#随机选择一个元素
print(random.sample(elements,2))#从L中随机选择n个元素
random.shuffle(elements)#随机重排L中元素
print(elements)
print(random.randint(1,5))#从m~n中随机选择一个整数

二、轮盘赌random

import random
def main():
    bankroll=int(input("Enter the mount os the bankroll:"))
    (amount,timesPlayed)=playDoubleOrNothing(bankroll)
    print("Ending bankroll:",amount,"dollars")
    print("Number of games played:",timesPlayed)
def isOdd(n):
    if (1<=n<=36) and (n % 2):
        return True
    else:
        return False
def profit(n):
    if isOdd(n):
        return 1
    else:
        return -1
def playDoubleOrNothing(bankroll):
    amount=bankroll
    timesPlayed=0
    while 0<amount<2*bankroll:
        n=random.randint(0,37)
        timesPlayed+=1
        amount+=profit(n)
        print(n,amount)
    print('ALL:',n, amount)
    return (amount,timesPlayed)
main()

E:\PycharmProjects\PythonStudy\venv\Scripts\python.exe E:/PycharmProjects/PythonStudy/test2.py
Enter the mount os the bankroll:4
5 5
14 4
24 3
27 4
14 3
25 4
7 5
19 6
6 5
9 6
13 7
13 8
ALL: 13 8
Ending bankroll: 8 dollars
Number of games played: 12

三、老.虎.机random

import  random
def main():
    for i in range(3):
        outcome=spinWheel()
        print(outcome,end="  ")
def spinWheel():
    n=random.randint(1,20)
    print(n)
    if n >15:
        return "Cherries"
    elif n>10:
        return  "Orange"
    elif n>5:
        return  "Plum"
    elif n>2:
        return "Melon"
    else:
        return "Bar"
main()

E:\PycharmProjects\PythonStudy\venv\Scripts\python.exe E:/PycharmProjects/PythonStudy/test2.py
1
Bar 10
Plum 3
Melon
Process finished with exit code 0 

四、随机数random.choice

import  random
freeThrow=["sucess","sucess","sucess","failure"]
print(random.choice(freeThrow))

E:\PycharmProjects\PythonStudy\venv\Scripts\python.exe E:/PycharmProjects/PythonStudy/test2.py
failure

Process finished with exit code 0

五、生成验证码

import random
checkcode = ''
for i in range(4):#0-4取i
    current = random.randrange(0,4)
    if current != i:
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print(checkcode)

输出:VDK3

 

posted @ 2018-09-16 01:21  航松先生  阅读(228)  评论(0)    收藏  举报