I'm trying to make a piece of code that will count up votes for three different candidates, and I'm using a function that uses the variable name (either A, B or C) as a parameter.
I'm trying to have it so that whenever a vote is counted for that candidate, it will call the function to increase the variable for that candidate by 1. However, with every way I've tried all 3 candidates will always have 0 votes counted, unless I completely remove the function.
I've tried several different ways of making the variables global variables but they all gave the same results.
A = 0
B = 0
C = 0
def after_vote(letter):
letter = letter + 1
print("Thank you for your vote.")
def winner(winner_letter, winner_votes):
print("The winner was", winner_letter, "with", str(winner_votes), "votes.")
while True:
vote = input("Please vote for either Candidate A, B or C. ").upper()
if vote == "A":
after_vote(A)
elif vote == "B":
after_vote(B)
elif vote == "C":
after_vote(C)
elif vote == "END":
print("Cadidate A got", str(A), "votes, Candidate B got", str(B), "votes, and Candidate C got", str(C), "votes.")
if A > B and A > C:
winner("A", A)
break
elif B > A and B > C:
winner("B", B)
break
elif C > A and C > B:
winner("C", C)
break
else:
print("There was no clear winner.")
break
else:
print("Please input a valid option.")
First of all, the idea is wrong. You don't want to handle global variables and pass names around. It could be done, but it is a bad idea.
A better option is to pass the variable to be modified to the function. However, the trick with integers is that they are immutable, so you cannot pass an integer to be modified by the function, as you would in C for instance.
What is left is either:
That was the theory, here is how to do it...
def after_vote(value):
print("Thank you for your vote.")
# Instead of modifying value (impossible), return a different value
return value + 1
A = after_vote(A)
class MutableInteger:
def __init__(value):
self.value = value
A = MutableInteger(0)
def after_vote(count):
# Integers cant be modified, but a _different_ integer can be put
# into the "value" attribute of the mutable count object
count.value += 1
print("Thank you for your vote.")
after_vote(A)
votes = {'A': 0, 'B': 0, 'C': 0}
def after_vote(votes, choice):
# Dictionaries are mutable, so you can update their values
votes[choice] += 1
print("Thank you for your vote.")
after_vote(votes, "A")
def after_vote(letter):
# Global variables are kept in a dictionary. globals() returns that dict
# WARNING: I've never seen code which does this for a *good* reason
globals()[letter] += 1
print("Thank you for your vote.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With