Why won't this simple python code work?


#1

Here is my code which should allow me to input any number (or character for that matter) and return with the absolute value of that number. If it isn’t a number it should return with “nope”. Unfortunately, when I run the code it only returns with “nope” even when I put in a number. Anyone see what it wrong with this?

n= raw_input(“Enter a number:”)
def distance_from_zero(n):
if type(n)== int or type(n)== float:
return abs(n)
else:
return “Nope”

print distance_from_zero(n)


#2

Do you know what data type n is? As what data type does raw_input store the result entered by the user? The code itself should give you the hint that even though you enter an integer or float, it isn’t stored by raw_input in that data type


#3

Oh so raw_input is storing data as unicode then? So how would I fix this problem so that it still checks that the input is a number?


#4

yes, which means text. which is of type string:

n= raw_input(“Enter a number:”)
if type(n) == str:
    print True

even when entering a number (integer or float), so that is slightly problematic.

Well, solving this problem is slightly challenging.

this stackoverflow question tackles the issue:

i like the use literal_eval in the second answer, it gives the right data type right away.

Each approach has its pro’s and cons, you can also go for the try and except in the first answer. But as you can see, both approaches use things you never heard of


#5

Right, I see how this gets complicated fast. Thanks for the help!


#6

yep, this gets complicated quit quickly.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.