0

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!

3
  • So you want var1=16 but print(var1) to show "10,12,14,16"? Perhaps you want each print to add to what you have already printed? Commented Nov 24, 2016 at 22:14
  • 1
    return the value of var1 as well in function3. And initialize it in function1. Refraining a downvote because Galaga is great. Commented Nov 24, 2016 at 22:14
  • whoever downvoted this, please go back to facebook or something. Commented Nov 24, 2016 at 22:16

2 Answers 2

1

You should use return in your function:

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

var1 = 10

def function3(v):
    return v + 2


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

        print(var1)
        clock.tick(5)

function1(var1)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I'm thinking of creating a class as @MK. suggested but return could also work.
This really is the "correct" way in Python as modifying global variables ruins modularization.
0

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.

1 Comment

Good to know. Thanks for your quick response! I'll look into creating a class...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.