Someone who votes twice
Predict the output · Medium · §11.3 Methods that change state
In this poll, each person can vote only once. Predict the output without running the code.
Code
class Poll:
def __init__(self, question):
self.question = question
self.yes = 0
self.no = 0
self.voters = []
def vote(self, name, answer):
if name in self.voters:
print("Already voted:", name)
return
self.voters.append(name)
if answer == "yes":
self.yes += 1
else:
self.no += 1
poll = Poll("Bibimbap for lunch?")
poll.vote("mina", "yes")
poll.vote("jun", "no")
poll.vote("mina", "no")
poll.vote("sora", "yes")
print(poll.yes, poll.no, len(poll.voters))Solve this problem in your browser
Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.