Celebrating Children's Day: A Random Gift Distributor Implemented in Python

insert image description here

Here is a simple Python program that will assign a gift to each child.

import random

# 儿童名字列表
children_names = ['小明', '小红', '小华', '小李', '小王']

# 礼物列表
gifts = ['玩具汽车', '巧克力', '泡泡机', '积木', '书籍']

def distribute_gifts(children_names, gifts):
    # 创建一个字典来存储每个儿童和他们的礼物
    gifts_for_children = {
    
    }

    # 遍历每个儿童名字
    for child in children_names:
        # 随机选择一个礼物
        gift = random.choice(gifts)
        
        # 将礼物添加到儿童的礼物列表中
        if child in gifts_for_children:
            gifts_for_children[child].append(gift)
        else:
            gifts_for_children[child] = [gift]
        
        # 从礼物列表中移除已经分配的礼物
        gifts.remove(gift)
    
    # 返回分配的礼物
    return gifts_for_children

# 调用函数,分配礼物
print(distribute_gifts(children_names, gifts))

When you run this program, it will randomly assign a gift to each child in the list, and print each child's name and the gift they got to the console. Note that for program simplicity, we assume that the number of gifts is the same as the number of children.

Happy Children's Day!

Guess you like

Origin blog.csdn.net/tuzajun/article/details/130980162