Review:Built_in Function I need your guys' help


I know the code is wrong,but if i don't want to type something like 'if type(x)==int or type(x)==float'.Because the code is a little long.What should i do to save some time.Thank you guys so much.

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


i don't know but your code works for me


If you try a string,the answer will not be 'False'


yeah , you are right , so this what i found

def distance_from_zero(x):
    if type(x) is (float or int):
        return abs(x)
        return 'Nope'
print distance_from_zero(-4)


Yeah,you're right.So it seems that we should see the code after 'is' as a whole.


I try your code again.I don't know why it doesn't work this time.


can reply to me the output error ??


yeah me to , i try it now didn't work :confused: i don't know why ??


I think the problem is the priority of '==' and 'or'.I try to use some brackets like the following:

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

but it still doesn't work.


This needs to be two complete expressions with nothing implicit; i.e., (int or float)...

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


I know that.I just want to explore a laconic way to type the code.Have any great idea?


In terms of expressions, we don't have ways to reduce them. They are the operands; However, Python has tuples that can be explored to this effect. Take a gander down that avenue and report back what you find. It will be interesting, for sure.


I've studied tuple yet.But i believe when i encounter the knowledge you say,the words you say will inspire me.


if you find anything let me know ( tag me )


def distance_from_zero(x):

if type(x) == int or type(x)==float:
    return abs(x)

    return 'Nope'

print distance_from_zero(10)

mucho mejor!!


We've already known how to solve this problem but then we tried to make the code easier.Have any great idea?


How about this :slight_smile:

def distance_from_zero(x):
    if type(x) in [float,int]:
        return abs(x)
        return 'Nope'



def distance_from_zero(x):
    return abs(x) if type(x) in [float,int] else 'Nope'


is the best i can do!