Python - “异常”语法错误

时间:2016-03-07 18:19:35

标签: python validation exception error-handling exception-handling

我正在尝试检查是否输入是一个整数,但我继续得到语法错误。代码如下,谢谢!

try:
    offset=int(input("How Much Would You Like To Offset By?\n"))
    except ValueError:
        while offset!=int:
            print("Please Enter An Integer!")
            offset=int(input("How Much Would You Like To Offset By?\m"))
            except ValueError

2 个答案:

答案 0 :(得分:2)

如评论中所述,您需要正确缩进代码。例如,您可以使用像Spyder这样免费且相对轻量级的IDE。此外,您的代码末尾还有一个except,不应该存在。但是,进一步详细查看代码,还有其他问题。您的while循环目前没有按预期执行,如果您使用的是Python 2.x,则需要将input替换为raw_input

try:
    offset=int(raw_input("How Much Would You Like To Offset By?\n"))
except ValueError:
    while offset!=int:
       print("Please Enter An Integer!")
       offset=int(input("How Much Would You Like To Offset By?\m"))

我怀疑你想做这样的事情,在你输入一个有效整数之前你一直要求用户输入:

offset = None

while not(offset):
    try:
        offset=int(input("How Much Would You Like To Offset By?\n"))
    except ValueError:
            print("Your input was not a valid number, please try again")
            offset = None

答案 1 :(得分:0)

你几乎就在那里,只是不完全。如评论中所述,您原始代码中的一个问题是第一个except的缩进。

一旦你解决了这个问题,你就会遇到第二个问题:

>>> def get_offset():
...     try:
...         offset=int(input("How Much Would You Like To Offset By?\n"))
...
...     except ValueError:
...         while offset!=int:
...             print("Please Enter An Integer!")
...             offset=int(input("How Much Would You Like To Offset By?\m"))
...             except ValueError
  File "<stdin>", line 9
    except ValueError
         ^
SyntaxError: invalid syntax
>>>

你从第二个except ValueError得到了这个问题,因为没有 try与之相关联。如果您修复此问题,则会出现错误,因为以下行在实际分配之前引用了offset的值:

while offset!=int:

如果初始尝试转换input()语句中输入的值失败,则实际上没有为offset分配值,这是导致此错误的原因。

我会按如下方式处理:

>>> def get_offset():
...     while True:
...         try:
...             offset = int(input("How Much Would You Like To Offset By?\n"))
...             break  # Exit the loop after a valid integer has been entered.
...
...         except ValueError:
...             print("Please enter an integer!")
...
...     return offset
...
>>> x = get_offset()
How Much Would You Like To Offset By?
5
>>> print(x)
5
>>> x = get_offset()
How Much Would You Like To Offset By?
spam
Please enter an integer!
How Much Would You Like To Offset By?
eggs
Please enter an integer!
How Much Would You Like To Offset By?
27
>>> print(x)
27
>>>

这允许您在输入有效整数之前不断查询偏移值。