value != float 或 value != int 无效
我正在尝试制作一个计算器,可以进行五种运算:加法、减法、乘法、除法和平方根。这些功能我都已经实现了,但在处理用户输入的值时,当输入的值是浮点数(小数)或整数时,出现了错误。我尝试用 value == str 来检查类型,但这样也不管用……有没有人能帮帮我?
比如说:
if value[0] != 'float' or value[0] != 'int' or value[1] != 'float' or value[1] != int':
return 'the input value is not correct
我尝试了上面提到的两种方法,但似乎都不行。程序无法区分浮点数、整数和字符串。
如果我输入:
calculator('+', 3, 4)
结果显示错误……
我使用 'print type(value[0], [1])' 是为了确认这些值的类型,以便找出导致错误的原因。
def calculator(sym, *t):
value = tuple(t)
n = len(value)
print type(value[0])
print type(value[1])
if value[0] != 'float' or value[0] != 'int' or value[1] != 'float' or value[1] != int':
return 'the input value is not correct.'
else:
if sym == '+':
if len(value) != 2:
return 'The input value is not correct.'
else:
return float(value[0] + value[1])
elif sym == '-':
if len(value) != 2:
return 'The input value is not correct.'
else:
return float(value[0] - value[1])
elif sym == '/':
if len(value) != 2:
return 'The input value is not correct.'
elif value[1] == 0:
return 'The input value is not correct.'
else:
return float(value[0] / value[1])
elif sym == '*':
if len(value) != 2:
return 'The input value is not correct.'
else:
return float(value[0] * value[1])
elif sym == 'sqrt':
if len(value) != 1:
return 'The input value is not correct.'
elif value[0] < 0:
return 'The input value is not correct.'
else:
return value[0] ** 0.5
else:
return 'The input value is not correct.'
`
2 个回答
1
你正在尝试比较值和字符串,而不是比较类型。应该使用isinstance()
函数来检查类型,它可以接受一个类型的元组:
if not (isinstance(value[0], (int, float)) and isinstance(value[1], (int, float))):
请注意,float
和int
在这里是名称,而不是字符串字面量。它们指的是内置的类型对象。
4
使用 isinstance
来检查数据类型:
>>> isinstance(1, int)
True
>>> isinstance(1, float)
False
>>> isinstance('str', int)
False
你可以使用 numbers.Number
来匹配任何类型的数字对象:
>>> import numbers
>>> isinstance(2, numbers.Number)
True
>>> isinstance(2.0, numbers.Number)
True