gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:22 25 4
gpt4 key购买 nike

我正在尝试编写一段代码来计算三个不同候选人的选票,并且我正在使用一个函数,该函数使用变量名称(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 中那样传递要由函数修改的整数。

剩下的是:

  • 传递一个值给函数,从函数返回修改后的值;或
  • 将一个包含值的可变对象传递给函数

这就是理论,下面是如何去做...

方案一:传一个值,返回修改后的值

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.")

关于python - 如何使用整数变量作为函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50401236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com