Review: built in functions. Unexpected error


#1

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)
    else:
        return 'Nope'


#2

Consider,

>>> isinstance(True, int)
True
>>>

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)
    else:
        return 'Nope'

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

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

https://docs.python.org/2/library/functions.html#isinstance


#3

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!"
else:
    print "Goodbye!"

The output is ...

Hello!

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):

#4

Along with this one:

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

	
word
>>>

#5

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