以下是一个 Python 抽奖系统,其中包含更多的功能,如添加参与者、多轮抽奖、保存获奖者名单等:
import random
import osdef load_participants():try:with open("participants.txt", "r") as file:participants = file.read().splitlines()return participantsexcept FileNotFoundError:return []def save_participants(participants):with open("participants.txt", "w") as file:file.write("\n".join(participants))def draw_winner(participants):if not participants:print("没有足够的参与者来进行抽奖。请添加参与者后再试。")returnwinner = random.choice(participants)print("恭喜 {} 获奖!".format(winner))return winnerdef main():participants = load_participants()while True:print("\n抽奖系统菜单:")print("1. 添加参与者")print("2. 进行抽奖")print("3. 退出")choice = input("请选择操作 (1/2/3): ")if choice == "1":name = input("请输入参与者的名字: ")participants.append(name)save_participants(participants)print("{} 已添加到参与者列表。".format(name))elif choice == "2":winner = draw_winner(participants)if winner:participants.remove(winner)save_participants(participants)elif choice == "3":print("抽奖系统已退出。")breakelse:print("无效的选择,请重新输入。")if __name__ == "__main__":main()
这个抽奖系统允许你添加参与者、进行抽奖,抽奖结果会从参与者列表中移除,并且可以多次运行。抽奖系统会将参与者保存在一个名为 “participants.txt” 的文本文件中,以便下次使用。
*效果展示: