Python练习9-14练习9-15分析
练习9-14 :random python
import random
jackpot = ['1', '2', '3', '4', '5', '6', '7',
'8', '9', '10', 'a', 'b', 'c', 'd', 'e']
winner_num = random.sample(jackpot, 4)
print(winner_num)
练习9-15 分析:
可以使⽤⼀个循环来明⽩前述⼤奖有多难中奖。为此,创建⼀个名为my_ticket 的列表或元组,再写⼀个循环,不断地随机选择数或字母,直到中⼤奖为⽌。请打印⼀条消息,报告执⾏循环多少次才中了⼤奖。
jackpot = ['1', '2', '3', '4', '5', '6', '7',
'8', '9', '10', 'a', 'b', 'c', 'd', 'e']
n = 1
my_ticket = random.sample(jackpot, k=4)
print(f"你的号码是 : {my_ticket};", end='')
while True:
winner_num = random.sample(jackpot, k=4)
if my_ticket != winner_num:
n += 1
# continue
else:
print(f"开奖 {n} 次,你才能赢得⼤奖")
break
for i in range(5):
print('%04.3f' % random.random(), end='')    #%04.3f 格式化已浮点的⽅式来显⽰数字,04表⽰左边显⽰4位数字位数不⾜0补齐,⼩数点后⾯的3表是⼩数点显⽰⼏位⼩数print()