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?
Try using
isinstanceto check fortype:Here you are checking that the variables are of the
strtype, and if either one of them is, you know a string is involved and will therefore not execute theelsecode.The
orcan 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 anorstatement is to useany, which checks if any of the conditions areTrueand executes if so:This comes in handy when you have a large data structure and need to do a similar
orcomparison. Theandequivalent isall, which has the same syntax, just usingallinstead ofany:And if you have a bunch of checks and get tired of typing
isinstance, you can bundle that part a bit further by using ageneratorin combination withanyorall: