【发布时间】:2021-01-16 06:52:33
【问题描述】:
我正在尝试用 Python 编写一个基本的井字游戏。我的功能之一是让用户输入为 1 到 9 之间的数字。如果用户输入非整数或不在 1 到 9 之间的数字,它将返回错误。它位于 try-except 中,以避免担心类型转换。
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 Code 中调试时,当调试器到达move = input("Type a number from 1-9: ") 行并单击“Step Into”时,它直接进入“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()
【问题讨论】:
-
Catch-all exceptions 是个坏主意,尤其是当它们只是丢弃实际错误时。你怎么知道异常是由输入的无效整数引起的?您应该捕捉到特定的错误,而通用的包罗万象的
except应该可以让您了解实际的潜在错误是什么。 -
这个问题是由
to_lower引起的(不是一个有效的str属性或方法) - 让它if move.lower() == "quit" or move.lower() == "exit": -
对于“不可重现或由错字引起”的近距离投票 - 我已修复错字,但问题仍未解决。
-
另外,如果反对者也能澄清问题需要改进的地方,我将不胜感激。如果你不告诉我它有什么问题,我应该如何提高问题质量?
标签: python python-3.x visual-studio-code