[SOLVED] The global variable from a function() within a different .py file isnt being found within Python script?

Issue

The ‘myName’ variable isn’t found when I use the following function from my func.py file. However, if I use the code directly into wordguess.py (rather than using a function version of it) the variable is found and it works.

def enter_name():
  global myName
    # Ask the a player for their username
  print("What is your username:")
  myName = input()[0:6]
  print("\n")
  while len(myName)==0:
    print("Please enter your username (Max 6 characters in length):")
    myName = input()
  print("Hi, " + str(myName) + ", welcome to the Word Guessing Game!")
  print("\n")

I then call func.enter_name() within the main script. I am using import func to include the func.py file. However i get the below error:

  File "wordguess.py", line 116, in main
    outputWriter.writerow({'Name' : myName, 'Date' : dtFullDate, 'Attempts' : attempts, 'Word Chosen' : wordChosen})
NameError: name 'myName' is not defined

If I instead paste the code within enter_name() directly into the main script it seems to work (I’ve looked at Using global variables in a function but can’t figure out the issue). This is the code which raises the error:

with open('scoreboard.csv', 'a', newline='') as outputFile:
        outputWriter = csv.DictWriter(outputFile, ['Name', 'Date', 'Attempts', 'Word Chosen'])
        outputWriter.writerow({'Name' : myName, 'Date' : dtFullDate, 'Attempts' : attempts, 'Word Chosen' : wordChosen})
        outputFile.close()

Not sure if the csv module has anything to do with the problem.

Solution

As per the advice from the comments:

  • I wrote the function call as func.enter_name()
  • Set ‘global myName’ within the enter_name() function
  • Used ‘func.myName’ when importing the variable

Answered By – Luca

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published.