-1

I have recently made the switch to Python 3 and regular things that usually work with Python 2 don't work with Python 3. I have been able to fix the rest but I am struggling with this one. I cannot check what "type" something is.

raw = input("Please give me a number, string\
 or decimal: ")
if type(raw) == int:
    print("You entered a number")
elif type(raw) == float:
    print("You entered a decimal")
elif type(raw) == str:
    print("You entered a string")
else:
    print("error please try again")

`

Pen_Fighter
  • 87
  • 2
  • 7

1 Answers1

5

In python3.x, input always returns an object of type str. The equivalent to python2.x would be eval(input('...')). As with using eval at any time, be sure that you absolutely trust that the input won't do malicious things to your program or computer...

A better way would be to use something like ast.literal_eval (which will safely evaluate your literals) or to do the checking yourself...

def is_int_str(s):
    """Checks if a string (s) represents a python integer."""
    try:
        int(s)
    except ValueError:
        return False
    return True

And it's trivial to then write the analogous float version...

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • there are isdigit/isnumeric methods in the string library that should probably be used here. – story645 Jul 26 '16 at 02:13
  • @story645 -- Nah... EAFP :-). Just `try` to convert the string to the appropriate type and see if it works ... – mgilson Jul 26 '16 at 02:13
  • meh, I like the string library for this...but really, just anything that isn't eval is probably good. – story645 Jul 26 '16 at 02:26