質問

I want to prompt the user with a separate exception error if they have entered a float over any other invalid string. Currently I get the same error if a string like "hello" is entered or a float like 2.5. Which exception should I be using just to filter float values? Thanks

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')
役に立ちましたか?

解決

The issue you're having is due to int raising the same exception for all invalid strings, whether they represent floats or just random text. Here's one way you could solve that:

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.")

他のヒント

Hmm... how about this?

x = input('Enter your choice: ')
if float(x) != int(x):
    raise TypeError
x = int(x)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top