Home > Mobile >  python - the scope of variables inside "main" function
python - the scope of variables inside "main" function

Time:11-27

This is my first post here, so please give me some constructive criticism (not too much).

My initial intent was to receive inputs from the user, and save them into variables to later user in other functions (in other modules).

This is a simplified version of what i am trying to do: i tried both with and without the "global inputfile" line, unsuccessfully. I also tried sending the variable as an argument to a function outside, it didnt work. I also tried importing the main module to the other module, it didnt work.

The code:

def main(argv):
    inputfile = "a"

if __name__ == "__main__":
    global inputfile
    print(inputfile)

gives me the following error:

NameError: name 'inputfile' is not defined

Thank you for your time.

CodePudding user response:

You need to call the function in order to acces the function value.

def main():
    global inputfile

    inputfile = "a"

if __name__ == "__main__":
    main()
    print(inputfile)

Gives #

a
  • Related