5

I'm working on a simple program that will ask for the weather and temperature and output what clothing the user should wear. However, I've gotten to the point where I want to make sure the user can't enter "g" degrees or any other string. Is there a simple way to compare variable types? In other words, is there something along the lines of:

if (type(temp) == 'str'):

    print("Invalid. Try again.")

Or something similar that isn't too complicated? Personally, I'm fine with using advanced functions and whatnot, but that would look sketchy to my CS teacher.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
William Adams
  • 51
  • 1
  • 1
  • 3
  • Check this out, there's a ton of information here: https://docs.python.org/2/library/string.html – ergonaut Oct 15 '15 at 02:26
  • Note that input read by `input()` in Python 3 and by `raw_input()` in Python 2 is always a string, even if it's a string of digits, so checking the type won't tell you anything. You'd have to try converting the string to another type, using e.g. `int(s)` or `float(s)`, as Makoto's answer shows. – deltab Oct 15 '15 at 02:36

4 Answers4

5

You pretty much have it right, just no need for the quotes.

>>> type(5) == int
True
>>> type('5') == int
False
>>> type('5') == str
True
user4020527
  • 1
  • 8
  • 20
4

It's easier to beg forgiveness than to ask permission.

Consider what most of us would do in this scenario (this assumes Python 3):

temp = int(input("Enter a numerical input: "))

If the input we get is not a number, we'll blow up with a ValueError. Knowing that, we should just...catch it:

try:
    temp = int(input("Enter a numerical input: "))
except ValueError as e:
    print("Invalid input - please enter a whole number!");

Don't fiddle with type checking, as this will make your code a bit less Pythonic. Instead, don't be afraid that this code has the chance to blow up; if it does, just catch the exception and deal with the aftermath later.

Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230
3

Python has a built in function for checking variable types. From the docs

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct, indirect or virtual) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

For example:

>>>n=3 
>>>isinstance(n, int)
True
>>>isinstance(n, str)
False
>>>m="example"
>>>isinstance(m, int)
False
>>>isinstance(m, str)
True
SnooDucks299792
  • 163
  • 1
  • 1
  • 11
PabTorre
  • 2,878
  • 21
  • 30
0

I just came across this and thought that although this question was asked a long time ago, for the benefit of other users, I'll put my solution up.

I created a helper function that checks for type by exception catching:

def TypeChecker(var):
    result = 1
    try:
        int(var)
   except:
        result = 2
   return 

Then in the main body of code, wherever I want to check for type identity I simply write something like this:

if TypeChecker(var1) == TypeChecker(var2):
    do_stuff...

This approach also allows the user to modify the variable type depending on that of another variable, since with this function, an int will return 1 and a string will return 2.

Brill
  • 11
  • 4