【问题标题】:Input statement isn't evaluated during debugging - triggers a Try Except调试期间不评估输入语句 - 触发 Try except
【发布时间】: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


【解决方案1】:

这很可能是因为在调试器中你没有标准输入的控制台,所以调用input() 会出错(我不知道具体的 VS 代码,所以我在这里猜测,但这是合理的原因)。

在任何情况下,我都强烈建议不要使用包罗万象的except 子句,因为这会沉默并错误地处理可能发生的错误,这些错误不属于您的预期流程的一部分。 p>

我首先将您的except 更改为except (ValueError, TypeError),以便它只捕获因输入/类型转换错误问题导致的错误。然后您将能够看到真正的错误是什么。

另外,请注意没有 move.tolower 这样的东西 - 您可能是指 move.lower()。也许这是你的错误?

【讨论】:

  • 谢谢,我使用了 tolower 的 Visual Basic 语法。我仍然收到错误 - 我已按照您的建议更改了 except 子句,现在调试器返回 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 &lt;module&gt; move = get_move()
  • 是的,很确定这意味着标准输入已在您的调试器中结束/关闭。弄清楚如何让 vscode 让你输入标准输入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 2020-07-06
  • 2015-06-15
  • 1970-01-01
  • 2013-04-10
  • 2018-06-16
  • 2011-11-29
相关资源
最近更新 更多