在 Python 中键入错误异常
TypeError Exception in Python
我是 python 的初学者,我们这周开始学习 OOP。我目前正在执行的程序计算矩形的面积并且我已经使大部分代码正常工作,除了程序需要拒绝浮点输入并退出的代码。
这是我的代码:
le = eval(input("Length:"))
wi = eval(input("Width:"))
def Rec(l, w):
if l < 0 and w < 0:
raise ValueError
total = l * w
return total
i = True
while i:
try:
print("Area:", Rec(le, wi))
i = False
except ValueError:
print("Input is negative!")
i = False
except TypeError:
print("The number is not an integer!")
i = False
else:
break
您可以检查输入的类型。
试试这个:
le = eval(input("Length:"))
wi = eval(input("Width:"))
import math
class Rec():
def __init__(self, l, w):
self.le = l
self.wi = w
def area(self):
if self.le < 0 or self.wi < 0:
raise ValueError
elif type(self.le) is float or type(self.wi) is float:
raise TypeError
else:
return self.le * self.wi
i = True
while i:
try:
total = Rec(le, wi)
print("Area:", total.area())
i = False
except ValueError:
print("Input is negative!")
i = False
except TypeError:
print("The number is not an integer!")
i = False
else:
break
您也可以使用 isinstance
而不是 type
,方法是将支票替换为:
elif isinstance(self.le,float) or isinstance(self.wi,float):
您还应该使用 or
检查长度或宽度是否为负数,而不是 ````and````` 因为两个维度都应该是正数。
您可以将输入包裹在支票中,如下所示:
def checkinput(x):
if(isinstance(x, int)):
return x
else:
print('Input a non decimal number like 1,2.. n.')
sys.exit(1) #exit with error code
le = checkinput(eval(input("Length:")))
wi = checkinput(eval(input("Width:")))
编辑:要完成这项工作,您还应该 'import sys'
我是 python 的初学者,我们这周开始学习 OOP。我目前正在执行的程序计算矩形的面积并且我已经使大部分代码正常工作,除了程序需要拒绝浮点输入并退出的代码。
这是我的代码:
le = eval(input("Length:"))
wi = eval(input("Width:"))
def Rec(l, w):
if l < 0 and w < 0:
raise ValueError
total = l * w
return total
i = True
while i:
try:
print("Area:", Rec(le, wi))
i = False
except ValueError:
print("Input is negative!")
i = False
except TypeError:
print("The number is not an integer!")
i = False
else:
break
您可以检查输入的类型。 试试这个:
le = eval(input("Length:"))
wi = eval(input("Width:"))
import math
class Rec():
def __init__(self, l, w):
self.le = l
self.wi = w
def area(self):
if self.le < 0 or self.wi < 0:
raise ValueError
elif type(self.le) is float or type(self.wi) is float:
raise TypeError
else:
return self.le * self.wi
i = True
while i:
try:
total = Rec(le, wi)
print("Area:", total.area())
i = False
except ValueError:
print("Input is negative!")
i = False
except TypeError:
print("The number is not an integer!")
i = False
else:
break
您也可以使用 isinstance
而不是 type
,方法是将支票替换为:
elif isinstance(self.le,float) or isinstance(self.wi,float):
您还应该使用 or
检查长度或宽度是否为负数,而不是 ````and````` 因为两个维度都应该是正数。
您可以将输入包裹在支票中,如下所示:
def checkinput(x):
if(isinstance(x, int)):
return x
else:
print('Input a non decimal number like 1,2.. n.')
sys.exit(1) #exit with error code
le = checkinput(eval(input("Length:")))
wi = checkinput(eval(input("Width:")))
编辑:要完成这项工作,您还应该 'import sys'