Gam*_*r01 3 python function global-variables parameter-passing python-3.x
我正在尝试制作一段代码来计算三个不同候选者的投票数,而我正在使用一个使用变量名称(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.")
Run Code Online (Sandbox Code Playgroud)
首先,这个想法是错误的.您不希望处理全局变量并传递名称.它可以做到,但这是一个坏主意.
更好的选择是将要修改的变量传递给函数.但是,整数的技巧是它们是不可变的,所以你不能传递一个整数来被函数修改,就像你在C中那样.
还剩下的是:
那就是理论,这里是怎么做的......
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
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.")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |