Brian Truong Brian Truong - 5 months ago 7
Python Question

My program is not giving the correct output?

I'm trying to get the absolute value of -2 to appear on python.

def distance_from_zero(a):

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

return abs(a)

else:

return "Nope"

distance_from_zero(-2)


The programs just says "None". I want it to give me the absolute value of -2 or say "nope" is the number is not an int or float.

Answer

Add print to see the output.

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

print distance_from_zero(-2)
print distance_from_zero('hi')

Output:

➜  python ./distance.py
2
Nope 

Demo