0

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.

Luca
  • 97
  • 7
  • You need to use `func.myName` when you import the variable from `func`. – Barmar Jan 24 '22 at 18:44
  • 3
    It would be better for the function to return a value rather than setting a global variable. – Barmar Jan 24 '22 at 18:45
  • 1
    "global" variables should probably be called "module global". So `func.enter_name()` will affect the global namespace *where `func.enter_name` is defined*, which is in `func`, so check for `func.myName` – juanpa.arrivillaga Jan 24 '22 at 19:10
  • I tried `outputWriter.writerow({'Name' : func.myName, 'Date' : dtFullDate, 'Attempts' : attempts, 'Word Chosen' : wordChosen})` however it says `AttributeError: module 'func' has no attribute 'myName'` Can you give an example please? Many thanks – Luca Jan 26 '22 at 10:32
  • and @juanpa.arrivillage – Luca Jan 26 '22 at 11:25

1 Answers1

1

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
Luca
  • 97
  • 7