python代碼的random子產品,常用函數是random.random,random.randint,random.randrange,random.choice,random.shuffle.
①random.random代表随機生成0-1之間的浮點數
②random.randint代表随機生成指定範圍的整數
③random.randrange代表随機生成指定範圍的整數,但不含最終值,步長為可選項
④random.choice代表在清單/元祖中随機選擇一個元素
⑤random.shuffle代表對清單/元祖中元素進行重新洗牌,相當于打亂原有的順序
抽獎代碼使用了random.choice,代碼示例如下:
import random #導入内置的random子產品
list1=list(range(0,15)) #将range元素進行清單轉換并指派給清單list1
print("抽獎号碼是:",list1) #列印所有的參與抽獎的号碼
list2=[] #定義空清單list2,用來儲存中獎号碼
while len(list1)>0:
result =random.choice(list1) #在清單list1裡選擇抽取的号碼并指派給result
if result in list1 and result%2==0 and result%3==0:
print("您的号碼是:{},恭喜您,您中一等獎".format(result))
list1.remove(result)
list2.append(result)
elif result%5==0:
print("您的号碼是:{},恭喜您,您中了二等獎".format(result))
list1.remove(result)
list2.append(result)
elif result%3==0:
print("您的号碼是:{},恭喜您,您中了三等獎".format(result))
list1.remove(result)
list2.append(result)
elif result%2!=0 and result%3!=0 and result%5!=0:
print("您的号碼是:{},您未中獎".format(result))
elif result==list1[-1] or result==list1[0]: #當抽取到清單list1最後一個或者第一個元素時
print("您的号碼是:{},抽獎結束".format(result)) #列印号碼,并列印抽獎結束
print("中獎名單是:", list2)
print("未中獎名單是:", list1)
break
代碼運作結果如下:
抽獎号碼是: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
您的号碼是:5,恭喜您,您中了二等獎
您的号碼是:10,恭喜您,您中了二等獎
您的号碼是:6,恭喜您,您中一等獎
您的号碼是:3,恭喜您,您中了三等獎
您的号碼是:13,您未中獎
您的号碼是:11,您未中獎
您的号碼是:14,抽獎結束
中獎名單是: [5, 10, 6, 3]
未中獎名單是: [0, 1, 2, 4, 7, 8, 9, 11, 12, 13, 14]
圖檔示例如下:
