Review:Built_in Function I need your guys' help


#1

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

#2

i don't know but your code works for me


#3

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


#4

yeah , you are right , so this what i found

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

#5

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


#6

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


#7

can reply to me the output error ??


#8

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


#9

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

but it still doesn't work.


#10

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

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

#11

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


#12

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.


#13

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


#14

if you find anything let me know ( tag me )


#15

def distance_from_zero(x):

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

else:
    return 'Nope'

print distance_from_zero(10)

mucho mejor!!


#16

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


#17

How about this :slight_smile:

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

#18

Or,

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

#19

is the best i can do!