TYL
TYL

Reputation: 1637

Variables not recognized after importing function from second script (Python)

I am calling a function from a second script but the variable from the first script is not recognized.

script1

selection = int(raw_input("Enter Selection: "))
if selection == 1:
    import script2
    script2.dosomething()

script2

def dosomething():
    while selection == 1:
    ......
    ......

It displays "NameError: global name 'selection' is not defined"

Is it something to do with global variables?

Upvotes: 1

Views: 887

Answers (2)

iamsankalp89
iamsankalp89

Reputation: 4739

I think you have to define that variable in other program, error itself says

"NameError: global name 'selection' is not defined"

Simply defined it

mySelection = selection
def dosomething(mySelection):
    while mySelection == 1:
       -------------

Upvotes: 0

Jorden
Jorden

Reputation: 653

That variable only "lives" within your first script. If you would like to use it in your other script, you could make it an argument to that function and do something like:

if selection == 1:
    import script2
    script2.dosomething(selection)

and in script2.py you would have:

def dosomething(selection):
    while selection == 1:
        ...

Upvotes: 5

Related Questions