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

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)

zvo*_*one 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)
Run Code Online (Sandbox Code Playgroud)

解决方案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)
Run Code Online (Sandbox Code Playgroud)

解决方案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")
Run Code Online (Sandbox Code Playgroud)

解决方案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.")
Run Code Online (Sandbox Code Playgroud)