strings and ints consistency - isinstance

Sayth Renshaw flebber.crue at gmail.com
Thu Sep 22 09:40:42 EDT 2016


> > 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.

Sadly imo clearer than the many hack attempts on SO.

> 
> > 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")
> 

True it failed, just actually happy to get it to fail or pass successfully on int input.

Just felt it was a clearer and more consistent approach to verifying input, then most of the varied and rather inconsistent approaches I have seen in trying to get this to work.

Half opt for try except the other half if else and then implement them largely differently. Every many and varied approach str2bool(), isalpha() using list with isinstance(var, [ int, str, bool]) etc.

Anyway back to the old drawing board.

Cheers

Sayth



More information about the Python-list mailing list