我正在尝试制作一段代码来计算三个不同候选人的选票,并且我正在使用一个使用变量名称(A,B或C)作为参数的函数。
我试图拥有它,以便每当为该候选人计算投票时,它都会调用该函数将该候选人的变量增加 1。但是,无论我尝试过哪种方式,所有 3 名候选人都将始终计算 0 票,除非我完全删除该功能。
我已经尝试了几种不同的方法来使变量成为全局变量,但它们都给出了相同的结果。
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.")
首先,这个想法是错误的。您不想处理全局变量并传递名称。这是可以做到的,但这是一个坏主意。
更好的选择是将要修改的变量传递给函数。但是,整数的诀窍在于它们是不可变的,因此您不能传递要由函数修改的整数,例如在 C 中。
剩下的是:
- 将值传递给函数,从函数返回修改后的值;或
- 将保存值的可变对象传递给函数
这就是理论,这是怎么做的...
解决方案 1:传递一个值,返回修改后的值
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)
解决方案 2:传递"可变整数">
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)
解决方案 3:传递所有投票的(可变!)字典
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")
解决方案4(最糟糕的!):实际按照您的要求进行操作
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.")
在您的情况下,最好定义 3 个函数,每个候选函数一个:
A = 0
B = 0
C = 0
def after_vote_A():
global A
A += 1
print("Thank you for your vote.")
def after_vote_B():
global B
B += 1
print("Thank you for your vote.")
def after_vote_C():
global C
C += 1
print("Thank you for your vote.")
不要忘记使用关键字global
,否则您可以定义局部变量。
另一种方法是将选票存储在dict
中:
votes = {'A': 0, 'B': 0, 'C': 0}
def after_vote(letter):
votes[letter] += 1
print("Thank you for your vote.")
演示:
after_vote('A')
after_vote('B')
after_vote('A')
after_vote('A')
print(votes)
你会得到:
Thank you for your vote.
Thank you for your vote.
Thank you for your vote.
Thank you for your vote.
{'A': 3, 'B': 1, 'C': 0}
最简单的方法是使用字典,如果没有两个候选人共享相同的名称。
candidates = {"A":0, "B":0, "C":0}
从那里,您可以设置一个函数来查找字典中的值并将其递增:
def update_vote(candidate):
candidates[candidate] += 1
或者,您可以就地更新投票,而不是使用以下方法调用函数:
candidates[candidate] += 1
一种更python化的方法是使每个候选人成为可以更新自己的投票计数的对象。
class Candidate(object):
def __init__(self):
# This is the "constructor" for the object.
# It is run whenever an instance of this object is created.
# We want it to "spawn in" with zero votes.
self.vote_count = 0
def update_vote(self):
self.vote_count += 1
这似乎更接近您在初始帖子中得到的内容。您将按如下方式创建一个对象:
A = Candidate()
B = Candidate()
C = Candidate()
然后,在你的主循环中,你只需告诉每个对象更新自己:
if vote == "A":
A.update_vote()
最后,当你计算选票时,你只需要要求每个对象给你他们的"投票"计数:
if A.vote_count > B.vote_count and A.vote_count > C.vote_count
您需要将可变数据类型传递到函数中,以便可以对其进行修改。尝试将您的候选人包装到列表或字典中。
candidates = {'A':0, 'B':0, 'C':0}
def after_vote(letter):
global candidates
if letter in candidates:
candidates[letter] += 1
print("Thank you for your vote.")
else:
print("No such candidate: Your vote is invalid.")