-3

Why does this function doesn't work?

int_myApples = 4    
int_yourApples = 13    
int_TotalApples = int_myApples + int_yourApples    

def giveApple():    
    int_yourApples += 1    
    int_myApples -=1    
    
giveApple()     
    
print("If I give you one of my apples,you have {} and I have {} apples.".format(int_yourApples,int_myApples))`

If I do the same without putting it into a function it just works.

int_yourApples += 1    
int_myApples -=1    
    
print("If I give you one of my apples, you have {} and I have {} apples.".format(int_yourApples,int_myApples))    

Any reason why?

AMC
  • 2,642
  • 7
  • 13
  • 35
KR BL
  • 1
  • 2
  • 4
    You haven't mentioned the error message you get, but if you searched it on here you would find lots of questions and answers explaining it. – khelwood Sep 18 '20 at 22:00
  • 1
    Duplicate: [Don't understand why UnboundLocalError occurs](https://stackoverflow.com/q/9264763/4518341) – wjandrea Sep 18 '20 at 22:02

1 Answers1

-1

A function needs global variables to call outside of the function, you can do it like this.

def giveApple():    
    global int_yourApples
    global int_myApples

    int_yourApples += 1    
    int_myApples -=1  
StarbuckBarista
  • 1,298
  • 1
  • 8
  • 20