从第二个脚本导入函数后无法识别变量(Python)

TYL*_*TYL 0 python variables

我从第二个脚本调用函数,但无法识别第一个脚本中的变量.

SCRIPT1

selection = int(raw_input("Enter Selection: "))
if selection == 1:
    import script2
    script2.dosomething()
Run Code Online (Sandbox Code Playgroud)

SCRIPT2

def dosomething():
    while selection == 1:
    ......
    ......
Run Code Online (Sandbox Code Playgroud)

它显示"NameError:全局名称'选择'未定义"

它与全局变量有关吗?

Jor*_*den 5

该变量仅在您的第一个脚本中"存在".如果您想在其他脚本中使用它,可以将其作为该函数的参数并执行以下操作:

if selection == 1:
    import script2
    script2.dosomething(selection)
Run Code Online (Sandbox Code Playgroud)

script2.py你会有:

def dosomething(selection):
    while selection == 1:
        ...
Run Code Online (Sandbox Code Playgroud)