Review: built in functions. Unexpected error


When I run my code it says "Oops, try again. "Your function seems to fail on input True when it returned '1' instead of 'Nope". i can't find out what;s wrong...

def distance_from_zero(num):
    if type(num) == int or float:
        return abs(num)
        return 'Nope'



>>> isinstance(True, int)

A boolean may be coerced to an integer by the above expression, and by type().

This is not expected by most new learners, and I'm not sure it is even mentioned before this exercise.

>>> def distance_from_zero(num):
    if type(num) == int or float and not isinstance(num, bool):
        return abs(num)
        return 'Nope'

>>> distance_from_zero(True)
>>> distance_from_zero(-1.2)
>>> distance_from_zero(-2)

Give the documentation a read to familiarize yourself with Python built-ins:


Hi @friendlymegalomaniac,

The isinstance function is useful for checking a type, as @mtf has indicated.

Also note that in this if block header ...

    if type(num) == int or float:

... the condition you are using does not test whether the type of num is equivalent to float. In your header, if the type of num is not equivalent to int, then the value of the entire condition is simply float, and that is treated as True when used as a condition. To verify that, try this as an experiment ...

if float:
    print "Hello!"
    print "Goodbye!"

The output is ...


To check whether num is an int or a float, you can do this ...

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

... or this ...

    if type(s) in (int, float):


Along with this one:

>>> x = 'word'
>>> if type(x) == int or float:
	print (x)



This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.