Hi I am curious if there is a way to convert user input to an specific variable type based off the content of the input (I'm using raw_input(), not sure if there's a better function for this). I know raw_input() always makes a string, but can said string be converted to an integer or a floating point if the input is valid? For example, if the user enters '1,' is there a way to have that variable stored as an integer rather than a string? Here is the code I am attempting to make work:
print "Subtraction Calculator (x-y)"
def calculator(x, y):
if [isinstance(x, int) or isinstance(x, float)] and [isinstance(y, int) or
isinstance(y, float)]: #This should be checking to see if x and y are both
numerical
D = x - y
return D
else:
return "One or more inputs is not a number."
x = raw_input("x = ")
y = raw_input("y = ")
print calculator(x, y)
Obviously this code doesn't work as x and y are both strings due to raw_input(), but I don't seem to be getting the proper error message ("One or more inputs is not a number.") and am instead getting an error at (D = x - y). I believe that this is due to my 'if' statement always registering as True, but I am not sure why this is either.
[isinstance(x, int) or isinstance(x, float)]is a non-empty list and thus true.