出于某种原因,我的代码认为全局变量是局部变量



所以我正在开发一个基本应用程序,按下一个按钮,它将数字添加到总数中,总数是一个全局变量,但程序的东西它是一个局部变量。

totalCarbs = 0
apple = 12
def addCarbsToTotal(food):
if food == "Apple":
print("Apple")
totalCarbs += apple
print(totalCarbs)

这是代码,任何帮助将不胜感激。

您需要在函数中指定变量的全局范围:

totalCarbs = 0
apple = 12
def addCarbsToTotal(food):
global totalCarbs, apple
if food == "Apple":
print("Apple")
totalCarbs += apple
print(totalCarbs)

totalCarbs(local( = totalCarbs(global( + apple 你可以这样做..

def addCarbsToTotal(food):
global totalCarbs
if food == "Apple":
print("Apple")
totalCarbs += apple
print(totalCarbs)

最新更新