简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM