strings and ints consistency - isinstance

Ned Batchelder ned at nedbatchelder.com
Thu Sep 22 06:19:12 EDT 2016


On Wednesday, September 21, 2016 at 11:41:42 PM UTC-4, 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 :-)
> 
> 
> answer = input("\t >> ")
> if isinstance(int(answer), int) is True:
>     raise ValueError("Ints aren't valid input")
>     sys.exit()
> elif isinstance(answer, str) is True:
>         print(v0 * t - 0.5 * g * t ** 2)
> else:
>     print("Ok please ammend your entries")
> 
> Cheers
> 
> Sayth

1) When checking for truth, there's very very rarely a need to use
"if x is True:".  Instead, just use "if x:"

2) "isinstance(int(answer), int)" will either be True, because the
int() call succeeded and produced an int, or the int() call will raise
an error.  Using it as a condition is baroque, and will never result
in the elif clause being tested.  So I'm not sure how your code is
ever printing the result of the calculation, or printing the
"amend" message.

Are you sure you've tested this code thoroughly?

--Ned.



More information about the Python-list mailing list