繁体   English   中英

在 Python 脚本中找不到来自 different.py 文件中的 function() 的全局变量?

[英]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 模块是否与该问题有关。

根据评论中的建议:

  • 我将 function 调用写为 func.enter_name()
  • 在 enter_name() function 中设置“全局 myName”
  • 导入变量时使用 'func.myName'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM