0

So I am working on a basic application, press a button and it adds the number to the total, the total is a global variable, but the program things it is a local variable.

totalCarbs = 0
apple = 12

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

Here is the code, any help would be appreciated.

Callum S
  • 213
  • 2
  • 10
  • you have to use `global totalCarbs` inside function - it is need when you want to change value in external variable using `=`, `+=`, etc. But it is not needed when you want to only get value from external value. BTW: Kivy usually use classes so maybe you should keep function and variable inside class and use `self.` – furas Jun 05 '20 at 09:49
  • 2
    Instead of using a global variable, pass `totalCarbs` as an argument and return it. [See also](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil). – Jan Christoph Terasa Jun 05 '20 at 09:51
  • The rule is very simple: if you assign to a variable (with `=`, `+=` ..) anywhere in the body of a function, this variable is considered local, unless you declare it as `global`. – Thierry Lathuille Jun 05 '20 at 09:54

2 Answers2

1

You need to specify the global scope of a variable inside a function:

totalCarbs = 0
apple = 12

def addCarbsToTotal(food):
    global totalCarbs, apple
    if food == "Apple":
        print("Apple")
        totalCarbs += apple
    print(totalCarbs)
ccl
  • 2,378
  • 2
  • 12
  • 26
1

totalCarbs(local) = totalCarbs(global) + apple you can do this..

def addCarbsToTotal(food):
    global totalCarbs
    if food == "Apple":
        print("Apple")
        totalCarbs += apple
    print(totalCarbs)
smitkpatel
  • 722
  • 6
  • 21