我正在尝试用Python编写一个基本的tic-tac-toe。我的一个功能是获取用户输入的1到9之间的数字。如果用户输入一个非整数或一个不在1和9之间的数字,它将返回一个错误。它只是一种尝试,只是为了避免担心类型转换
def get_move():
print("Your move ...")
while True:
try:
move = input("Type a number from 1-9: ")
if move.isnumeric():
if (0 < int(move) < 10):
break
else:
print("The number is outside the range. Try again.")
else:
if (move.tolower == "quit") or (move.tolower == "exit"):
exit()
except:
print("Not a valid integer, try again.")
return move
当我正常运行时,这种方法会起作用。但是当我尝试在VS代码中调试时,当调试器到达第move = input("Type a number from 1-9: ")
行并单击“单步执行”时,它直接转到“except”子句。代码在一个无限循环中运行——它永远不会停止并等待用户输入,这意味着我必须手动停止调试器
知道为什么会这样吗
编辑:
谢谢你纠正我的打字错误,但这并没有解决问题。我已将行更改为:
if (move.tolower == "quit") or (move.tolower == "exit"):
exit()
致:
if move.lower() == "quit" or move.lower() == "exit":
exit()
并且还将except
子句更改为except (ValueError, TypeError)
。现在我收到以下错误:
Exception has occurred: EOFError
EOF when reading a line
File "[...]tictacpy.py", line 18, in get_move
move = input("Type a number from 1-9: ")
File "[...]tictacpy.py", line 46, in <module>
move = get_move()
最有可能发生这种情况的原因是,在调试器中,您没有用于标准输入的控制台,因此调用
input()
将出错(我不知道具体的VS代码,所以我在这里猜测,但这是一个合理的原因)在任何情况下,我强烈建议不要使用所有的catching
except
子句,因为这会使可能发生的错误保持沉默,并且错误地处理这些错误,而这些错误不是您期望的流的一部分首先,我将您的
except
改为except (ValueError, TypeError)
,以便它只捕获由错误的输入/类型转换问题导致的错误。然后,您将能够看到真正的错误是什么另外,请注意,没有
move.tolower
这样的东西-您可能是指move.lower()
。也许那是你的错误相关问题 更多 >
编程相关推荐