-1

The problem is my program can't increment variable 'x'.

This is code from the main.py:

from functions import increment

x = 1

print('x =',x)
increment()
print('x =',x)

This is the code from functions.py:

def increment():
    global x
    x += 1

And I'm receiving error "name 'x' is not defined". Help, I'm beginner.

Michał Kluz
  • 29
  • 1
  • 5

2 Answers2

2

Global in the context you put does not work across modules... if you did something like this, however, it would work

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print globvar     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

see more here

Community
  • 1
  • 1
deweyredman
  • 1,440
  • 1
  • 9
  • 12
1

The variable x doesn't be global in other modules, if you initial it as global in your function ,the global keyword makes a variable global inside its module that been loaded . So you need to simply pass your variable as argument to function and then return the result :

def increment(x):
    x += 1
    return x

And in the main code , you can call the function as following :

x=increment(x)
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    Huh? Do you mean `x = increment(x)`? Changing the value inside the function and returning it will not change the original value. – paulmelnikow Feb 04 '15 at 03:15