練習9-14 彩票:
創建一個列表或元組,其中包含10個數和5個字母。從這個列表或元組中隨機選擇4個數或字母,並打印一條消息,指出只要彩票是這4個數或字母,就中大獎了。
1 import random 2 3 jackpot = list(range(10)) + ['a', 'l', 'o', 't', 'n'] 4 winning_number = random.sample(jackpot, k=4) 5 print(f"If your number is {winning_number}, then congrats! you win the lottery")
練習9-15 彩票分析:
可以使用一個循環來明白前述彩票大獎有多難中獎。為此,創建一個名為my_ticket 的列表或元組,再寫一個循環,不斷地隨機選擇數或字母,直到中大獎為止。請打印一條消息,報告執行循環多少次才中了大獎。
1 import random 2 3 jackpot = list(range(10)) + ['a', 'l', 'o', 't', 'n'] 4 5 n = 1 6 while True: 7 winning_number = random.sample(jackpot, k=4) 8 print(f"If your number is {winning_number}, then congrats! you win the lottery") 9 my_ticket = random.choices(jackpot, k=4) 10 if winning_number != my_ticket: 11 n += 1 12 continue 13 else: 14 print(f"It takes you {n} times to win the lottery") 15 break
1 import random 2 3 jackpot = list(range(10)) + ['a', 'l', 'o', 't', 'n'] 4 winning_number = random.sample(jackpot, k=4) 5 print(f"If your number is {winning_number}, then congrats! you win the lottery") 6 7 n = 1 8 while True: 9 my_ticket = random.choices(jackpot, k=4) 10 if winning_number != my_ticket: 11 n += 1 12 continue 13 else: 14 print(f"It takes you {n} times to win the lottery") 15 break