Exception 在Python3中使用try/except
如果用户在任何其他无效字符串上输入了浮点数,我想用一个单独的异常错误提示用户。目前,如果输入像“hello”这样的字符串或像2.5这样的浮点,我会得到相同的错误。我应该使用哪个异常来过滤浮点值?谢谢Exception 在Python3中使用try/except,exception,python-3.x,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):
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')
print('为选项1输入1')
打印('为选项2'输入2')
打印('为选项3'输入3')
打印('输入4退出')
flag=True
x=-1
而(旗):
尝试:
x=(int(输入('输入您的选择:'))
如果((x>=1)和(xHmm),这个怎么样
x = input('Enter your choice: ')
if float(x) != int(x):
raise TypeError
x = int(x)
您遇到的问题是由于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.")
为True时:
尝试:
s=输入(“输入数字1-4”)
x=int(x)#如果不能将s转换为int,则会产生值错误
如果1