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".

6
  • What you need to archive here ? Commented Feb 16, 2018 at 9:17
  • 2
    Can you please describe your problem a little bit more? What is your expectation? Where should result be stored? Commented Feb 16, 2018 at 9:17
  • 2
    result is a local var of function main(). If you want to use result outside of main() type 'global result' (without qoutes) in the body of main() Commented Feb 16, 2018 at 9:21
  • 2
    What do you mean "stored" ? "stored" where ? Commented Feb 16, 2018 at 9:27
  • in python3 it works tho. Commented Feb 16, 2018 at 9:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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
    ......

2 Comments

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.