Beside your syntax errors possible due to the copy paste, you need to check if the type of a is an int
(float) not a type(int)
(type float
).
In python also types have a type: the type "type".
>>> a = 1
>>> type(a)
<class 'int'>
>>> type(int)
<class 'type'>
so your check should be:
if type(a) is int or type(a) is float:
...
Edit: In your comment you said it didn't work, so I put a snippet with the complete code so you can see it works and compare it to yours to see where you did different.
In [2]: def dist_frm_zero(a):
...: if type(a) is int or type(a) is float:
...: return abs(a)
...: else:
...: print('not possible')
...:
In [3]: dist_frm_zero(10)
Out[3]: 10
In [4]: dist_frm_zero(-0.432)
Out[4]: 0.432
In [5]: dist_frm_zero("Ciao")
not possible
Another two things about your question.
Fix the position of your print
statement. In that position is a syntax error, and if intended to be in the if
, it would still be after a return so it'll never be executed.
A function that sometimes returns a number, sometimes returns None
and prints a statement it's not the best from many points of view. A better solution would be to assert
the input is correct or to raise a TypeError
exception. Another solution would be to omit the checks and let the exception be thrown directly by the abs
function which when an input with the wrong type is passed throws the following:
>>> abs("ciao")
TypeError: bad operand type for abs(): 'str'
So two better solutions would be:
def dist_frm_zero(a):
return abs(a)
def dist_frm_zero(a):
if type(a) not in [int, float]:
raise TypeError("a must be an int or a float")
return abs(a)