dummy dummy - 6 months ago 16
Python Question

Review: Built-In Functions

This is a two-parter: first, define a function, distance_from_zero, with one parameter (choose any parameter name you like).

Second, have that function do the following:

Check the type of the input it receives.
If the type is int or float, the function should return the absolute value of the function input.
If the type is any other type, the function should return "Not an integer or float!"

code:

def distance_from_zero(n):
print type(n)
if type(n) == int or type(n) == float:
var = abs(n)
print var
return n
else:
print "no!"
return n

var = input("Enter number:")
print var
distance_from_zero(var)

Answer

First, as the others have suggested, use raw_input().

Then, you can try to convert it to an int or float. If both of those fail, you don't have a number. If you want to keep the "original" type, you can use this:

def distance_from_zero(n):
    try:
        n = int(n)
    except ValueError:
        try:
            n = float(n)
        except ValueError:
            print "Not a number!"
            n = float("NaN")
    return abs(n)

If you don't mind if the input 1 is converted to 1.0, then you can simplify the function:

def distance_from_zero(n):
    try:
        return abs(float(n))
    except ValueError:
        print "Not a number!"
        return float("NaN")  # or remove this line to return None

In both cases, you would call the function like this:

var = raw_input("Enter number: ")
print distance_from_zero(var)