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