python投票系统代码怎么写

   2025-02-15 5980
核心提示:以下是一个简单的Python投票系统的代码示例:class VotingSystem:def __init__(self):self.candidates = {}# 候选人字典,存储候

以下是一个简单的Python投票系统的代码示例:

class VotingSystem:    def __init__(self):        self.candidates = {}  # 候选人字典,存储候选人及其得票数    def add_candidate(self, candidate):        if candidate not in self.candidates:            self.candidates[candidate] = 0            print(f"候选人 {candidate} 添加成功!")        else:            print(f"候选人 {candidate} 已存在!")    def vote(self, candidate):        if candidate in self.candidates:            self.candidates[candidate] += 1            print(f"投票成功!候选人 {candidate} 当前得票数为 {self.candidates[candidate]}")        else:            print(f"候选人 {candidate} 不存在,请先添加候选人!")    def get_results(self):        sorted_candidates = sorted(self.candidates.items(), key=lambda x: x[1], reverse=True)        print("投票结果:")        for candidate, votes in sorted_candidates:            print(f"候选人 {candidate} 得票数:{votes}")# 创建投票系统对象voting_system = VotingSystem()# 添加候选人voting_system.add_candidate("张三")voting_system.add_candidate("李四")voting_system.add_candidate("王五")# 进行投票voting_system.vote("张三")voting_system.vote("李四")voting_system.vote("李四")voting_system.vote("王五")# 查看投票结果voting_system.get_results()

以上代码定义了一个VotingSystem类,包含添加候选人、投票和获取投票结果等功能。可以根据需要进行扩展和修改。运行代码可以看到候选人添加成功、投票成功的提示信息,以及最终的投票结果。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言