newtonjeep newtonjeep - 1 year ago 122
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
clock = pygame.time.Clock()

var1 = 10

def function3(var1):

var1 = var1 + 2

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


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!

Answer Source

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

var1 = 10

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

print var1
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download