在Python 3中使用try / except

时间:2014-03-04 00:42:45

标签: exception python-3.x

如果用户在任何其他无效字符串上输入了浮点数,我想提示用户单独出现异常错误。目前,如果输入“hello”之类的字符串或2.5之类的浮点数,我会得到相同的错误。我应该使用哪个例外来过滤浮点值?感谢

print('Enter 1 for option 1')
print('Enter 2 for option 2')
print('Enter 3 for option 3')
print('Enter 4 to quit')

flag = True
x = -1
while(flag):

        try:
            x  = (int(input('Enter your choice: ')))
            if((x >= 1) and (x <= 4)):
                flag = False
                x = x
            else:
                print('The number should be between 1 and 4')
        except TypeError:
            print('Choice should be an integer not a float')
        except ValueError:
            print('Choice should be a number')
        except NameError:
            print('Choice should be a number')

2 个答案:

答案 0 :(得分:3)

您遇到的问题是由于int为所有无效字符串引发了相同的异常,无论它们是浮点数还是随机文本。这是你可以解决的一种方法:

while True:
    try:
        s = input("Enter a number 1-4")
        x = int(x)      # this will raise a ValueError if s can't be made into an int
        if 1 <= x <= 4:
            break
        print("The number must be between 1 and 4")
    except ValueError:
        try:
            float(s)    # will raise another ValueError if s can't be made into a float
            print("You must enter an integer, rather than a floating point number.")
        except ValueError:
            print("You must enter a number.")

答案 1 :(得分:0)

嗯......这个怎么样?

x = input('Enter your choice: ')
if float(x) != int(x):
    raise TypeError
x = int(x)