The below has no synthetical or static semantic errors in it, but does not run as expected. Namely, I want my shell to print "string involved" if the type of varA or varB is string; instead it prints nothing. Could anyone help me understand what is wrong with my code and how to fix it?
varA = 1
varB = "A"
if (type(varA) and type(varB)) is (int or float):
if varA > varB:
print("bigger")
if varA == varB:
print("equal")
if varA < varB:
print("smaller")
elif (type(varA) or type(varB)) is str:
print("string involved")
well, that's one hell of a script..
if (type(varA) and type(varB)) is (int or float):
is same as
if str is int: # and that evaluates to False
and
elif (type(varA) or type(varB)) is str:
is same as
elif int is str: # again evaluates to False
for better understanding read
https://python-forum.io/Thread-Multiple-...or-keyword
that said, checking types in Python is not common practice. Read
duck typing
finally, varA is int and varB is str, comparison betwen different types could yield unexpected results
>>> 1>'A'
False
>>> 1=='A'
False
>>> 1<'A'
True
>>>
Usually input is taken as strings. So usually both variables would be a string. In that case you could utilize string methods such as
str.isdigit()
Otherwise you should use the isinstance built in rather than type..
if isinstance(varA, (int, float)) and isinstance(varB, (int, float)):
if varA > varB:
print("bigger")
elif varA == varB:
print("equal")
elif varA < varB:
print("smaller")
elif isinstance(varA, str) or isinstance(varB, str):
print('string involved')
However in python you should ask for forgiveness rather than permission. You can do any variation of try/except here, but here is
a version. I kept the checking for string, because you can still make those comparisons with strings, otherwise the if condition wouldn't even be there.
if isinstance(varA, str) or isinstance(varB, str):
print('string involved')
else:
try:
if varA > varB:
print("bigger")
elif varA == varB:
print("equal")
elif varA < varB:
print("smaller")
except TypeError:
pass
(Oct-02-2017, 02:44 PM)Shellburn Wrote: [ -> ]The below has no synthetical or static semantic errors in it, but does not run as expected.
You don't know what a semantic error is, then.