Asking for raw_input when defining functions


#1

I was doing the last sections for the lesson functions (19.)
I tried to be a little creative with my code and tried:

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

print distance_from_zero(raw_input)

However, the interpreter is still evaluating my code to print "Nope".

Can anybody help?

Thanks in advance
:slightly_smiling:


#2

raw_input is a function, it's not an int and it's not a float, so your function says Nope.

If you want the raw_input to do something, how do you execute a function? And would it give you integers or floats? Or would you have to do some converting first?


#3

Ah, thanks. That answers my question.

In regards to the questions you're asking me, I don't quite understand. But you've responded with is sufficient.

Thanks again


#4

A function is executed by calling it. We do that by adding () after the name.

raw_input returns a string, but your function expects a float, or an int. So the string would need to be parsed by either the float type or the int type before you can send that input to your function.


#5

Sorry for the v. late reply. That gave me a better understanding. Could you tell me how I'd go about parsing the string input to float or an int?


#6

@tes_py: To convert a string to number, like an integer, you'll need to use the function int() and for float, float().
Here's an example:

Best regards,
G4be


#7

Sorry if I wasn't clear, but I meant with raw input() function. How do I parse a string to a float or an int with the raw input() function?


#8

@tes_py: You'll get the input from the user using raw_input() and all you'll need to do is to put that same function inside either of int() or float()

Best regards,
G4be