1

I am trying to make a game, but I have run into a roadblock I cannot figure out. this is the part of my code that I am failing to understand

from random import randint
apple = (0, 0)
def placeApple():
    apple = (randint(0, 19), randint(0, 19))
    fillCell(apple[0] * 20, apple[1] * 20, appleColor)
print(apple)

I feel like this should change apple to a point with a random integer 0 through 19 but when I call print(apple) in the console I always get (0, 0)

Astrocow
  • 75
  • 4

2 Answers2

1

Yes, you can you can declare global apple (not recommended):

def placeApple():
    global apple
    apple = (randint(0, 19), randint(0, 19))
    fillCell(apple[0] * 20, apple[1] * 20, appleColor)

Or return it:

def placeApple():
    apple = (randint(0, 19), randint(0, 19))
    fillCell(apple[0] * 20, apple[1] * 20, appleColor)
    return apple

But for either of these you actually have to call the function, e.g. for the return option:

apple = placeApple()
print(apple)
AChampion
  • 29,683
  • 4
  • 59
  • 75
1

The problem you are facing is that you have a global variable called apple, and inside your function you have a local variable also called apple. If you want to modify a global variable inside your function you should use global:

def placeApple():
    global apple
    apple = (randint(0, 19), randint(0, 19))
    fillCell(apple[0] * 20, apple[1] * 20, appleColor)

placeApple()

print(apple)

However, changing global variables inside functions is a very bad practice since it could cause you a headache when you have to debug. With this approach, apple will be updated every time you call placeApple.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228