John McIntyre Jr. John McIntyre Jr. -3 years ago 130
Python Question

Unable to use variables from another file in Python

I have declared a few variables and initialised them with some value in

Contents of :

flag = 0
j = 1

I want to use those values in another file : like:
Contents of

import variables
if(flag == 0) :
j = j+1

However I get the following error,

NameError: name 'flag' is not defined

How can i solve this problem?

Answer Source

Everything you've done is right except when using the variables.

In your file:

if(variables.flag == 0) :
    variables.j = variables.j + 1


Use the following header :

from variables import *


from variables import flag, j

Replace all the references of flag and j (or any other variable you want to use from that file) with the prefix 'variables.'

Since this is just a copy of the variable, the values in the won't get affected if you modify them in

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