strings and ints consistency - isinstance

Steve D'Aprano steve+python at pearwood.info
Thu Sep 22 06:58:23 EDT 2016


On Thu, 22 Sep 2016 01:41 pm, Sayth Renshaw wrote:

> This ends being the code I can use to get it to work, seems clear and
> pythonic, open to opinion on that :-)

Neither clear, nor Pythonic.


> answer = input("\t >> ")

Since input() returns a string in Python 3, this will always be a string.


> if isinstance(int(answer), int) is True:

int(answer) will either succeed, or it will fail. If it fails, it will raise
ValueError, and your code will fail with an exception.

If it succeeds, then it will return an int. Testing whether int(answer)
returns an int is a waste of time -- it *always* returns an int, if it
returns at all. So if it returns, it will return an int, isinstance() will
always return True, and True is True. So your code will then

>     raise ValueError("Ints aren't valid input")

Which means your code will ALWAYS raise ValueError:

if answer is a numeric string, like "123", then int() will succeed, the if
block will run, and ValueError is raised;

but if answer is NOT a numeric string, like "abc", then int() will raise
ValueError.

So we can replace your entire block of code with a single line:

raise ValueError

since that is the only result possible. The rest of your code is dead
code -- it cannot be executed.

But if it could...


>     sys.exit()

It seems a bit harsh to exit the application just because the user types the
wrong value. Shouldn't you try again, let them type another string?


> elif isinstance(answer, str) is True:
>         print(v0 * t - 0.5 * g * t ** 2)

Since input() returns a string, answer is always a string, and isinstance()
will always return True. So True is True will always evaluate to True, and
the print statement with the mysterious formula will always print.


> else:
>     print("Ok please ammend your entries")

That can never occur, since both the if... clause and the elif... clause
will always evaluate as True. So this is dead code.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list