1

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?

TYL
  • 1,577
  • 20
  • 33
  • 1
    You didn't define selection. It is not a parameter in your function – whackamadoodle3000 Feb 16 '18 at 04:34
  • Possible duplicate of [Global Variable from a different file Python](https://stackoverflow.com/questions/3400525/global-variable-from-a-different-file-python) – Spencer Wieczorek Feb 16 '18 at 04:41
  • `selection` was defined in `script2`'s scope, so it gives you a `NameError`. There are a couple ways to get `selection` into `script2`'s scope: pass it in as a variable, define `script1` and `script2` in the same file with `script1` in the same or higher scope, or define `selection` as `global`. See https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules – IceArdor Feb 16 '18 at 04:42
  • 1
    @IceArdor But `selection` is global in this case. – Spencer Wieczorek Feb 16 '18 at 04:43
  • Where's the `global` keyword? It isn't `global`. – IceArdor Feb 16 '18 at 04:46
  • @IceArdor Yes it is. It's defined in the global scope which means it's a global variable. The `global` keyword is only relevant in a local scope. See: https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python – Spencer Wieczorek Feb 16 '18 at 04:48

2 Answers2

5

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:
        ...
Jorden
  • 653
  • 5
  • 11
0

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:
       -------------
iamsankalp89
  • 4,607
  • 2
  • 15
  • 36