python投票系统代码怎么写

37次阅读
没有评论

共计 1011 个字符,预计需要花费 3 分钟才能阅读完成。

以下是一个简单的 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 类,包含添加候选人、投票和获取投票结果等功能。可以根据需要进行扩展和修改。运行代码可以看到候选人添加成功、投票成功的提示信息,以及最终的投票结果。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计1011字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)