Skip to content Skip to sidebar Skip to footer

Python: Checking Type Of Variables

I have a question about python. I have variables a, b, c and d. And I have the following line: if not isinstance(a, int) or not isinstance(b, int) \ or not isinstance(c, i

Solution 1:

U should use all:

ifnotall(isinstance(var, (int, float)) forvarin [a, b, c, d]):
    # do stuff

Note, that you can supply both int and 'float' to the isinstance call.

Solution 2:

Try the following:

>>>a = 1>>>b = 1.0>>>c = 123>>>d = 233>>>any((type(var) in (int, float) for var in [a,b,c,d]))
True
>>>c = 'hello'>>>any((type(var) in (int, float) for var in [a,b,c,d]))
True
>>>

Solution 3:

>>>a = b = c = d = []>>>any(notisinstance(x, (int, float)) for x in [a,b,c,d])
True
>>>d = 0>>>any(notisinstance(x, (int, float)) for x in [a,b,c,d])
False

Solution 4:

Actually, what you've write is equal to

ifTrue:
    do_somthing
    pass

Solution 5:

Clearly, you didn't take enough attention to the RemcoGerlich's comment, since you upvoted and accepted a senseless answer. At the time I write this, 4 other people upvoted the same senseless answer. That's incredible. Will you see better with this ? :

defOP(a,b,c):
    returnnotisinstance(a, int)\
           ornotisinstance(b, int)\
           ornotisinstance(c, int)\
           ornotisinstance(a, float)\
           ornotisinstance(b, float)\
           ornotisinstance(c, float)

defAZ(a,b,c):
    returnall(isinstance(var, (int, float))
               for var in [a, b, c])

gen = ((a,b,c) for a in (1, 1.1 ,'a')
       for b in (2, 2.2, 'b') for c in (3, 3.3, 'c'))

print'                  OPv | AZv     OPv is AZv\n'\
      '                 -----|-----    -----------'
OPV_list = []
for a,b,c in gen:
    OPv = OP(a,b,c)
    OPV_list.append(OPv)
    AZv = AZ(a,b,c)
    print'%3r  %3r  %3r    %s | %s      %s'\
          % (a,b,c,OPv,AZv,OPv is AZv if OPv isnot AZv else'')

print'-------------    ----'print'all(OPV_list) : ',all(OPV_list)

result OPv = yours AZv = senseless answer I limited to a,b,c to make it short

                  OPv | AZv     OPv is AZv
                 -----|-----    -----------123True|True123.3True|True12'c'True|FalseFalse12.23True|True12.23.3True|True12.2'c'True|FalseFalse1'b'3True|FalseFalse1'b'3.3True|FalseFalse1'b''c'True|FalseFalse1.123True|True1.123.3True|True1.12'c'True|FalseFalse1.12.23True|True1.12.23.3True|True1.12.2'c'True|FalseFalse1.1'b'3True|FalseFalse1.1'b'3.3True|FalseFalse1.1'b''c'True|FalseFalse'a'23True|FalseFalse'a'23.3True|FalseFalse'a'2'c'True|FalseFalse'a'2.23True|FalseFalse'a'2.23.3True|FalseFalse'a'2.2'c'True|FalseFalse'a''b'3True|FalseFalse'a''b'3.3True|FalseFalse'a''b''c'True|FalseFalse-------------    ----all(OPV_list) :  True

Post a Comment for "Python: Checking Type Of Variables"