针对多种类型检查变量的类型不会产生预期的结果 [英] Checking type of variable against multiple types doesn't produce expected result
本文介绍了针对多种类型检查变量的类型不会产生预期的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任务:
- 使用一个参数定义函数
distance_from_zero
. - 让该函数执行以下操作:
- 检查它收到的输入的类型.
- 如果类型为
int
或float
,则函数应返回函数输入的绝对值. - 如果类型是任何其他类型,则函数应返回
"Not an integer or float!"
- Define a function,
distance_from_zero
with one parameter. - Have that function do the following:
- Check the type of the input it receives.
- If the type is
int
orfloat
, the function should return the absolute value of the function input. - If the type is any other type, the function should return
"Not an integer or float!"
我的答案不起作用:
def distance_from_zero(d):
if type(d) == int or float:
return abs(d)
else:
return "Not an integer or float!"
推荐答案
您不能使用这种基于自然语言的逻辑串联".我的意思是,您需要明确说明逻辑条件的各个部分.
You cannot use this kind of "natural language based logic concatenation". What I mean is that you need to state the parts of your logical conditions explicitly.
if type(d) == int or type(d) == float
这样,您将拥有两个比较,它们分别代表:if type(d) == int
和type(d) == float
.可以将其结果与or
运算符组合.
This way you have the two comparisons, which stand for themselves: if type(d) == int
as well as type(d) == float
. The results of this can be combined with the or
-operator.
这篇关于针对多种类型检查变量的类型不会产生预期的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文