我彻底搜索了我的问题的答案,但找不到任何可以解释我的结果的东西 . 我真的希望你们中的任何人都能指出我正确的方向 .
目前,我正在尝试使用Python 3编写基于文本的冒险游戏,以便更好地理解语言 .
在这样做时,我创建了一个函数,应该根据用户输入询问 user 的 input 和 print a specific statement . In case users input 是 invalid 该函数应该 keep asking for input 直到它有效 .
Unfortunately the function only seems to keep asking for input, without ever executing the if/elif statements within the function. Due to no errors being shown I am currently at a loss as to why this is the case...
print("If You want to start the game, please enter 'start'." + "\n" +
"Otherwise please enter 'quit' in order to quit the game.")
startGame = True
def StartGame_int(answer):
if answer.lower() == "start":
startGame = False
return "Welcome to Vahlderia!"
elif answer.lower() == "quit":
startGame = False
return "Thank You for playing Vahlderia!" + "\n" + "You can now close
the window."
else:
return "Please enter either 'r' to start or 'q' to quit the game."
def StartGame():
answ = input("- ")
StartGame_int(answ)
while startGame == True:
StartGame()
1 回答
你陷入了范围陷阱:你在函数内部创建了一个新的变量
startGame
,在你离开它之后就被丢弃了 . 你需要修改全局的:其他SO问题可能会引起关注:
Python scoping rules
Asking the user for input until they give a valid response
Use of global keyword
和我一直最喜欢的:
最后一个将帮助您弄清楚为什么您返回的文本不会被打印,以及为什么
if
不能用于'r'
或'q'
以及您遇到的其他任何问题 . 它还会告诉你if
确实被执行了; o)为了避免其他初学者陷阱,您可以阅读其他有关文本冒险的好东西:
How to copy or clone a list
How to parse a string to float or int
How to randomly select an item from a list