1

I am a c++ programmer and am learning pygame so I am very new to python. I noticed this behavior of functions and don't know what to do about it:

let's say we have a global variable:

x = 10

Now let's say we have a function that changes the value of x:

def foo():
    x = 100

Now, inside my main pygame loop, if I call foo(), the variable x is still 10 after the function call. How is this happening???

Kingsley
  • 14,398
  • 5
  • 31
  • 53

2 Answers2

0

Inside the function local scope value of x is changed. The x defined outside the function has global scope. To change global value try global var_name statement inside function before updating value

def foo():
  global x
  x = 100
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

Inside your function, you implicitly create another variable x, and then set it to 100. To change the global variable try this:

 def foo(): 
              global x
              x = 100