Python抽奖程序生成三组不同的随机数

由 碎念_Nian 发布

Python抽奖程序生成三组不同的随机数


方法一:

import random


def lottery():                                          # 抽奖程序
    for i in range(1, head_count + 1):                  # 抽奖总人数循环写入列表
        personnel_list.append(i)
    print(f'人数列表:{personnel_list}')

    third_prize = random.sample(personnel_list, 3)      # 在人数列表中取三个随机数
    print(f'三等奖:{third_prize}')

    for third_prize in third_prize:                     # 在人数列表中删除已获得三等奖的元素
        personnel_list.remove(third_prize)

    second_prize = random.sample(personnel_list, 2)     # 在人数列表中取两个随机数
    print(f'二等奖:{second_prize}')

    for second_prize in second_prize:                   # 在人数列表中删除已获得二等奖的元素
        personnel_list.remove(second_prize)

    first_prize = random.sample(personnel_list, 1)      # 在人数列表中取一位随机数
    print(f'一等奖:{first_prize}')


head_count = input('输入需要参与抽奖总人数(数值不得小于6):')
personnel_list = []                                     # 创建空列表 后续用于写入人数列表
if head_count.isdigit():                                # 判断输入的内容是否只由数字组成
    head_count = int(head_count)                        # 若输入的内容只由数字组成 则转为整数型
    if head_count >= 6:                                 # 3 + 2 + 1 = 6 因此人数必须大于等于6
        lottery()                                       # 若人数大于等于6 则运行抽奖程序
    else:
        print('数值过小')                                # 若人数小于6 则提示数值过小
else:
    print('输入错误')                                    # 若输入的内容不只是由数字组成 则提示输入错误

方法二:

import random


def lottery():                                 # 抽奖程序

    random_list = random.sample(range(1, head_count + 1), head_count)   # 生成一组随机数
    print(f'随机列表:{random_list}')

    print(f'三等奖:{random_list[0:3]}')        # 取随机列表的第1 - 3位

    print(f'二等奖:{random_list[3:5]}')        # 取随机列表的第4 - 5位

    print(f'一等奖:{random_list[5:6]}')        # 取随机列表的第6位


head_count = input('输入需要参与抽奖总人数(数值不得小于6):')
personnel_list = []                                     # 创建空列表 后续用于写入人数列表
if head_count.isdigit():                                # 判断输入的内容是否只由数字组成
    head_count = int(head_count)                        # 若输入的内容只由数字组成 则转为整数型
    if head_count >= 6:                                 # 3 + 2 + 1 = 6 因此人数必须大于等于6
        lottery()                                       # 若人数大于等于6 则运行抽奖程序
    else:
        print('数值过小')                                # 若人数小于6 则提示数值过小
else:
    print('输入错误')                                    # 若输入的内容不只是由数字组成 则提示输入错误