如何使用整数变量作为函数的参数?

时间:2018-05-17 22:16:57

标签: python python-3.x function global-variables parameter-passing

我试图制作一段代码来计算三个不同候选人的选票,我使用的函数使用变量名称(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.")

4 个答案:

答案 0 :(得分:5)

首先,这个想法是错误的。您不希望处理全局变量并传递名称。它可以做到,但这是一个坏主意。

更好的选择是将要修改的变量传递给函数。但是,整数的技巧是它们是不可变的,所以你不能传递一个整数来被函数修改,就像你在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.")

答案 1 :(得分:2)

在您的情况下,最好定义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}

答案 2 :(得分:2)

最简单的方法是使用dict,如果没有两个候选人共享同一个名字。

else{
                animation3.setOnFinished(event -> balance.setValue(1));
                fadeB();
            }

从那里,您可以设置一个函数来查找字典中的值并递增它:

candidates = {"A":0, "B":0, "C":0}

或者哎呀,你可以就地更新投票,而不是用以下方式调用函数:

def update_vote(candidate):
    candidates[candidate] += 1

这样做的更多pythonic方法是让每个候选人成为可以更新自己投票数的对象。

candidates[candidate] += 1

这似乎更接近您在初始帖子中所获得的内容。您可以按如下方式创建对象:

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()

答案 3 :(得分:1)

您需要将可变数据类型传递给函数,以便您可以对其进行修改。尝试将候选人包装成列表或字典。

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.")
相关问题