Python, boolean resets itself

1.6k Views Asked by At

I'm using python and I'm making a game, but there's one thing I don't get.

Why does this boolean reset? I don't want boolean 'powerup' to reset.

def spawnPowerup()
    number = 0
    powerup = False

    if (a certain thing happens, the thing happens for one frame.):
        number = random.randint(1,2)

    if number == 1 or powerup == True:
        print(powerup)
        powerup = True
        print(powerup)

The idea behind this code is, whenever the thing happens, I get a number. When the number is equal to 1, the powerup should be activated, but since the number in changing the whole time I need this boolean. So whenever the number is equal to 1 I change the boolean falue, so the if statement will always be true when the number has been equal to 1. But the problem is that the boolean resets. If the thing happens a couple of times this will be printed:

False
True
False
True
False
True
False
True
3

There are 3 best solutions below

2
On BEST ANSWER

powerup is set to False every time this function is called. So when you're hitting:

if number == 1 or powerup == True:
        print(powerup)
        powerup = True
        print(powerup)

number must be 1 if you enter that block (unless you have other code that is not shown). So when you do your first print, powerup is still False. You set to True, then print again

0
On

Here's what's confusing you:

if number == 1 or powerup == True:
    print(powerup)
    powerup = True
    print(powerup)

It will only print the value of powerup here. At the first print statement, the value is always False, while afterwards, it is True. You will only print it out when the if block is executed, changing powerup to True. To explore more on this, just add a print(powerup) before the if block.

1
On

You always set the boolean to False when you enter the function, so naturally it is being reset. But this is a local variable; it doesn't exist outside the function anyway.