Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
不带GOTO的Python错误处理_Python_Python 3.x_Error Handling - Fatal编程技术网

不带GOTO的Python错误处理

不带GOTO的Python错误处理,python,python-3.x,error-handling,Python,Python 3.x,Error Handling,我目前正在使用以下代码行获取用户输入: qty = int(input("How many of this item should we start with?")) 正如人们所期望的,如果输入的值不能转换为INT,它将抛出一个错误 出现错误时,我想提示“请输入一个整数”,并返回到请求输入的前一行。实现这一点最“通灵”的方法是什么?也许,最通灵的方法是做以下事情 while True: try: qty = int(input("How many of this ite

我目前正在使用以下代码行获取用户输入:

qty = int(input("How many of this item should we start with?"))
正如人们所期望的,如果输入的值不能转换为INT,它将抛出一个错误


出现错误时,我想提示“请输入一个整数”,并返回到请求输入的前一行。实现这一点最“通灵”的方法是什么?

也许,最通灵的方法是做以下事情

while True:
    try:
        qty = int(input("How many of this item should we start with?"))
        break
    except ValueError:
        pass     

也许,最具python风格的方法是执行以下操作

while True:
    try:
        qty = int(input("How many of this item should we start with?"))
        break
    except ValueError:
        pass     

“实现这一点最“Pythonic”的方法是什么?”简言之:使用
while
循环
try/except
。有关更多信息,请参阅上面的链接。您已经尝试了哪些内容?你在谷歌上搜索过“python中的用户输入错误处理”或类似的东西吗?“实现这一点的最“Pythonic”的方法是什么?”简而言之:使用
while
循环
try/except
。有关更多信息,请参阅上面的链接。您已经尝试了哪些内容?你在谷歌上搜索过“python中的用户输入错误处理”或者类似的东西吗?注意:这个问题是针对python 3.x的,所以
input
是你想要的,而不是
raw\u input
(它只存在于Py2上)。啊,好的,更新。pass是否再次将其返回到提示?提示返回是因为
循环继续运行时,
pass
告诉它在看到错误时不做任何操作。@NickSentowski
pass
实际上什么也不做。它被用在空的街区。while循环将其返回,因为异常情况下将无法到达
break
。注意:问题是针对Python3.x标记的,因此
input
是您想要的,而不是
raw\u input
(仅在Py2上存在)。啊,好的,更新。pass是否再次将其返回到提示?提示返回是因为
循环继续运行时,
pass
告诉它在看到错误时不做任何操作。@NickSentowski
pass
实际上什么也不做。它被用在空的街区。while循环将其带回,因为在异常情况下将无法到达
break