用python写一个投票系统
时间: 2024-05-08 07:20:51 浏览: 4
好的,下面是一个简单的投票系统的代码示例:
```python
class Poll:
def __init__(self, question, options):
self.question = question
self.options = options
self.votes = [0] * len(options)
def vote(self, option):
if option in self.options:
index = self.options.index(option)
self.votes[index] += 1
else:
print("Invalid option!")
def results(self):
print(self.question)
for i in range(len(self.options)):
print(f"{self.options[i]}: {self.votes[i]}")
# 示例用法
poll = Poll("Which is your favorite color?", ["Red", "Green", "Blue"])
poll.vote("Red")
poll.vote("Green")
poll.vote("Red")
poll.results()
```
这个投票系统使用了一个类 `Poll`,来表示一个投票。在初始化时,需要提供问题和选项,以及每个选项的初始投票数(默认为 0)。
投票时,用户需要提供选项名称,系统会自动找到对应的选项并将其投票数加 1。如果提供的选项名称不在选项列表中,则视为无效选项。
最后,可以使用 `results` 方法来输出当前投票的结果,包括问题和每个选项的投票数。