19. Review: Built-in Functions


#1



For this code I'm receiving the error message: Oops, try again. Your function seems to fail on input -9.5 when it returned 'Nope' instead of '9.5'

However when I replicate it in the Python shell it functions as intended. Is this a bug in exercise?
I know the set answer requires me to enter

if type(arg) == int or type(arg) == float

but my way is still fine right?


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


#2

if you add a function call:

def distance_from_zero(arg):
    
    if type(arg) == (int or float):
        return abs(arg)
        
    else:
        return "Nope"
    
print distance_from_zero(-9.62)

you can clearly see that that the wrong thing is returned.

can i see a screenshot of you running the code in shell?


#3


#4

Oh wait, I just tried it with a float and it returns "Nope". My bad, is there a reason putting them in brackets doesn't work? I just assumed that it would evaluate to true if it was an integer or float.


#5

i was just going to say exactly this.

no, because parentheses are evaluated first:

(int or float)

which is evaluated, and results in int, so then the comparison becomes:

if type(arg) == int

if you want to do this, you get:

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

#6

Ohhhh ok I get it. Thanks for your help!


#7

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