问题
The following piece of code is showing an error:
if ((type(varA) or type(varB) ) == type('t')):
print "string involved"
elif varA<varB:
print "RANDOM"
the error is for this case:
Test Values: varA = 0, varB = adios
output:
RANDOM
while this other piece of code
if ((type(varA) == type('t')) or (type(varB)== type('t'))):
print "string involved"
elif varA<varB:
print "RANDOM"`
For the following test values:
Test Values: varA = 6, varB = adios
ouput is as follows:
string involved
What is the difference between these two "if" conditions? I am finding them to be of the same logic!
回答1:
The problem is this expression:
if ((type(varA) or type(varB) ) == type('t')):
Programming languages don't work like English. The above first evaluates type(varA) or type(varB)
, which will yield the type of varA
- because or
returns the first truthy value and any type is truthy.
Then it will check to see if that is the same as type('t')
- that is, str
. Which means that it will only be true when varA
is a string, and the type of varB
is completely ignored.
What you want is probably this:
if type(varA) == type('t') or type(varB) == type('t'):
But there are more idiomatic/Pythonic ways of doing that; see Óscar López's answer for some examples.
回答2:
This is wrong:
if ((type(varA) or type(varB) ) == type('t')):
It should be:
if type(varA) == str or type(varB) == str:
Equivalently:
if isinstance(varA, str) or isinstance(varB, str):
Or a bit shorter:
if str in ((type(varA), type(varB)):
回答3:
If you want the test to work well for subclasses of str
as well it's a good idea to use isintance
instead of type
if any(isinstance(x, str) for x in (varA, varB)):
...
来源:https://stackoverflow.com/questions/19485061/python-if-else-statements