Python 点票程序:实现简单选举投票系统
要实现点票,你需要定义一个字典来存储每个候选人的得票数。然后,每次有人投票时,你需要更新相应候选人的得票数。以下是一个示例代码:
candidates = {'Candidate A': 0, 'Candidate B': 0, 'Candidate C': 0}
while True:
vote = input('Please enter the name of the candidate you want to vote for (or 'quit' to exit): ')
if vote == 'quit':
break
if vote in candidates:
candidates[vote] += 1
print('Thank you for voting!')
else:
print('Invalid candidate name. Please try again.')
print('The final vote count is:')
for candidate, votes in candidates.items():
print(candidate + ': ' + str(votes))
在这个示例代码中,我们首先定义了一个字典 candidates 来存储每个候选人的得票数,初始值都为零。
然后,我们使用一个无限循环来接收用户的投票。每次用户输入候选人的名字时,我们检查是否是有效的候选人名字。如果是,我们就将相应候选人的得票数加一,并输出感谢信息;否则,我们输出无效候选人名字的提示信息。
最后,我们遍历字典 candidates,输出每个候选人的得票数,以显示最终的选举结果。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/nA9c 著作权归作者所有。请勿转载和采集!