newtonjeep newtonjeep - 15 days ago 9
Python Question

Modifying a variable in Python

I'm creating a Galaga clone with pygame and I am having issues with using a value in one function that was modified in other function. I created a very simple version of the code to try to debug it but I have not had any luck.

import pygame
import time
pygame.init()
clock = pygame.time.Clock()

var1 = 10

def function3(var1):

var1 = var1 + 2


def function1():
gameExit = False
while not gameExit:
function3(var1)

print(var1)
clock.tick(5)
function1()


My question is (based on this simplified version) how do I display the updated value of var1. I would like print(var1) to display 10,12,14,16...

My guess is to use a global declaration but the closest question that I found on stackexchange was this and it didn't seem to work with my scenario.

Please note that I'm aware that this increase of var1 could be done with a while loop but a while loop will not work with my actual code. I would like an answer (or hint) that utilizes this format (as shown above).

Any suggestions would be appreciated. Thanks!

MK. MK.
Answer

Here is "correct" way of doing what you want:

var1 = 10

def function3():
    global var1
    var1 = var1 + 2

print var1
function3()
print var1

Your code is modifying local variable var1 which is only defined within your function3. I put word correct in quotes because global variable is (almost) never a good idea. If you need state (variable) shared between multiple functions, you could create a class. Or you could be modern functional and immutable and have the function take a value as argument, modify and return it.