练习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