teja kaipa teja kaipa - 5 months ago 11
Python Question

how can i make this variable t global , so that it can be used in all functions

I am using

t
as global and assigned
t
value from the
s1
,
s2
functions
but after
person1
it is not going to
person2
. And the error is as below

File "C:\Users\Teja kaipa\Desktop\estimation.py", line 42, in person1
if (t>1):
NameError: name 't' is not defined
global t


Code:

def s1():
t=1
return t
def s2():
t=2
return t
def s3():
t=3

def person1():
output = 0
val1 = int(r1e1.get())
val2 = int(r1w1.get())
if ((val1-val2)==0):
output = 1+2*val1
else:
output = -2*abs(val1-val2)
r1n1m.delete(0, END)
r1n1m.insert(4,str(output))
if (t>1):
person2()

def person2():
val1= int(r1e2.get())
val2= int(r1w2.get())
if ((val1-val2)==0):
output = 1+2*val1
else:
output = -2*abs(val1-val2)
r1n2m.delete(0, END)
r1n2m.insert(4,str(output))
if (t>2):
person3()

Answer

Inside each module where you want to modify the global variable, explicitly specifying t as a global variable.

def func1():
    global t
    t = 3

def func2():
    global t
    t = [1,2,3]

def main():
    global t
    func1()
    print t
    func2()
    print t

The output should be:

3
[1, 2, 3]