[英]The global variable from a function() within a different .py file isnt being found within Python script?
當我從我的 func.py 文件中使用以下 function 時,找不到“myName”變量。 但是,如果我直接在 wordguess.py 中使用代碼(而不是使用它的 function 版本),則會找到變量並且它可以工作。
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")
然后我在主腳本中調用func.enter_name()
。 我正在使用import func
來包含 func.py 文件。 但是我收到以下錯誤:
File "wordguess.py", line 116, in main
outputWriter.writerow({'Name' : myName, 'Date' : dtFullDate, 'Attempts' : attempts, 'Word Chosen' : wordChosen})
NameError: name 'myName' is not defined
如果我將 enter_name() 中的代碼直接粘貼到主腳本中,它似乎可以工作(我查看了Using global variables in a function但無法解決問題)。 這是引發錯誤的代碼:
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()
不確定 csv 模塊是否與該問題有關。
根據評論中的建議:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.