I need help with Review:Built in Fuctions


Here is my code...

def distance_from_zero(number):
if type(number) == int or float:
return abs(number)
return "Nope"

If I submit this code, I get this response.

Oops, try again. Your function seems to fail on input True when it returned '1' instead of 'Nope'

If I change type(number) == int or float to type(number) == int or type(number) == float

I get the correct answer, but I don't understand why my original code was wrong.

Could someone explain to me why?


I think this is just how Python works, or to be more specific how or works.
You can "divide" your if statement and you get something like
if [type(number)==int] or [float] which doesn't make any sense


I figured out what was wrong with my code.


Hi @textsolver19729 ,

The expression that serves as the condition in this line consists of two sub-expressions, connected by an or operator ...

if type(number) == int or float:

The sub-expressions are ...


... and ...


With an or operator, if either sub-expression is True, the expression is True.

Note that type(number) does not appear in the second sub-expression. The value, float, is a type, and if it is evaluated as a boolean expression, it qualifies as True. Therefore, the condition in this line is always True, regardless of the type of number ...

if type(number) == int or float:

That line does not serve the purpose that you intended. Use this, instead ...

if type(number) == int or type(number) == float: