1

My code is:

varA = 5
varB = 'dog'
if type(varB) == 'string':
    print("string involved")
elif type(varA) == 'string':
    print("string involved")
else:
    if varA > varB:
        print("bigger")
    elif varA == varB:
        print("equal")
    elif varA < varB:
        print("smaller")

I get error on line 8. I want the code not to react on line 7 else statement, if it has already met the requirements for if(line3) or elif(line5)!

Also, how to use 'or' method so it joins toget if(line3) and elif(line5) statements?

tshepang
  • 12,111
  • 21
  • 91
  • 136
5brickbomzh
  • 99
  • 1
  • 4
  • 12

2 Answers2

4

Try using isinstance to check for type:

varA = 5
varB = 'dog'
if isinstance(varA, str) or isinstance(varB, str):
    print("string involved")
else:
    if varA > varB:
        print("bigger")
    elif varA == varB:
        print("equal")
    else:
        print("smaller")

Here you are checking that the variables are of the str type, and if either one of them is, you know a string is involved and will therefore not execute the else code.

The or can be done by essentially combining the two conditions into one line, as in the example. Here it isn't a big issue, another way you can simulate an or statement is to use any, which checks if any of the conditions are True and executes if so:

if any((isinstance(varA, str), isinstance(varB, str))):
    # Code...

This comes in handy when you have a large data structure and need to do a similar or comparison. The and equivalent is all, which has the same syntax, just using all instead of any:

if all((isinstance(varA, str), isinstance(varB, str))):
    # This code will evaluate if all values are strings

And if you have a bunch of checks and get tired of typing isinstance, you can bundle that part a bit further by using a generator in combination with any or all:

if any(isinstance(x, str) for x in (varA, varB)):
    # Code
RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
0

What's happening is that type() returns a type object, not a string, so you are comparing type(varB) = <type 'str'> with the actual string string, and they are not the same.

Then you compare 5 and a string, which throws an error because there is no way to compare them.

This SO question explains in detail a bunch of different ways to check types.

Community
  • 1
  • 1
Matthew Adams
  • 9,426
  • 3
  • 27
  • 43