【发布时间】:2021-02-01 16:40:14
【问题描述】:
我正在尝试编写一个石头、纸、剪刀的游戏,但我收到一个关于我导入的文件没有“quitGame”属性的错误,即使我应该将该变量与其他人。
这是具有quitGame 变量的函数(过滤掉不需要的部分):
def playRps():
game = "".join([playerAction, computerAction])
global quitGame
outcomes = {
"rr": tied,
"pp": tied,
"ss": tied,
"rp": playerLoss,
"ps": playerLoss,
"sr": playerLoss,
"rs": playerWin,
"pr": playerWin,
"sp": playerWin,
}
if playerAction == "q":
quitGame = True # TODO: Figure out why this isn't working in the main.py file
else:
action = outcomes.get(game)
if action:
action()
else:
print("Invalid input!")
你也可以找到整个functions.py文件here.
这是应该运行程序的main.py 文件(过滤掉不需要的部分):
import functions # Imports the functions.py file
while True:
playGame = str(input('Would you like to play "Rock, Paper, Scissors"? (Y/n): '))
if playGame == "y":
while True:
functions.playerChoice()
functions.computerChoice()
functions.playRps()
if functions.quitGame == True:
break
elif playGame == "n":
print("Terminating program...")
quit()
else:
print("Unknown input. Please enter a valid answer.")
continue
你也可以找到整个main.py文件here.
这是我试图修复的错误的交互:
(.venv) johnny@lj-laptop:rock_paper_scissors$ /home/johnny/Projects/rock_paper_scissors/.venv/bin/python /home/johnny/Projects/rock_paper_scissors/main.py
Would you like to play "Rock, Paper, Scissors"? (Y/n): y
Rock, paper, or scissors?
Acceptable responses are...
"r": Chooses rock.
"p": Chooses paper.
"s": Chooses scissors.
"q": Quits the game.
r
Tied! No points awarded.
Traceback (most recent call last):
File "/home/johnny/Projects/rock_paper_scissors/main.py", line 18, in <module>
if functions.quitGame == True:
AttributeError: module 'functions' has no attribute 'quitGame'
我觉得这很奇怪,因为 playerScore 和 computerScore 等其他变量按预期工作。我在每个变量和函数之前添加了functions.,所以它为什么告诉我我没有它是没有意义的。
我什至在创建变量的函数中添加了global quitGame。我不明白为什么这不起作用。
我的问题是:
- 为什么我在调用该变量时会出错?我做错了什么?
【问题讨论】:
-
作为一名程序员,您应该非常、非常、非常努力不使用全局变量。
-
也许你可以不用全局并从 playRps() 返回
True或False。 -
@LiterallyJohnny 你可以使用一个类。您可以从函数返回变量。您也可以使用 Google 来帮助寻找答案。以下是一些:stackoverflow.com/questions/59330578/…stackoverflow.com/questions/11462314/…
-
@LiterallyJohnny
if playRps() == False确实是正确的语法。这是非常基本的 Python,我建议学习有关如何使用函数的基本教程。 -
我建议您在接受互联网陌生人的话之前,确保您了解全球员工的好处和陷阱。全局变量确实要付出高昂的代价,但如果你不知道为什么要避开它们,你就不知道什么时候应该不避开它们。
标签: python