1

I am running script 2 from script 1 but the output of script 2 is not stored as a variable in script 1.

script1

def main():
    selection = int(raw_input("Enter Selection: "))
    if selection == 1:
        a = 1
        import script2
        result = script2.doit(a)
        print result
        return True

    elif selection == 0:
        return False

while main():
    pass

print result

script 2

def doit(a):
    return a+2

Although result gets printed after an iteration, it is not stored as "result" after I end the loop. print result outside the loop gives the error "NameError: name 'result' is not defined".

TYL
  • 1,577
  • 20
  • 33

2 Answers2

1

It's because a is a local variable. When your main function returns a value, local variables are cleared. You should either pass it as reference or return the value and re-assign to a global variable.

Chuk Ultima
  • 987
  • 1
  • 11
  • 21
1

Adding global result to the main body of main() does the job. Credits to A False Name for the answer. Thanks!

def main():
    global result
    ......
TYL
  • 1,577
  • 20
  • 33
  • Using `global` does work. But it's highly discouraged to use `global`, because it will make your code very very confusing and hard to debug. Instead, use `return` to pass back any result you want to use in the calling scope. Also, it's best to keep all imports at the top of the file, and not nested inside functions. – Håken Lid Feb 16 '18 at 09:40
  • https://stackoverflow.com/questions/19158339/why-are-global-variables-evil – Håken Lid Feb 16 '18 at 09:42