strings and ints consistency - isinstance
Sayth Renshaw
flebber.crue at gmail.com
Wed Sep 21 23:33:06 EDT 2016
To answer all the good replies.
I adapted a simple vector example from the Springer book practical primer on science with python.
Having solved the actual problem I thought checking with the user they had the correct entries or would like to ammend them would be a good addition. This leads to the question Y or N response which isn't hard but if someone accidentally types 4, then you get where I got stuck can't test an int for ValueError if you expect a string.
This was my code
import sys
v0 = float(input("What velocity would you like? "))
g = float(input("What gravity would you like? "))
t = float(input("What time decimal would you like? "))
print("""
We have the following inputs.
v0 is %d
g is %d
t is %d
Is this correct? [Y/n]
""" % (v0, g, t))
while True:
try:
answer = input("\t >> ").isalpha()
print(v0 * t - 0.5 * g * t ** 2)
except ValueError as err:
print("Not a valid entry", err.args)
sys.exit()
finally:
print("would you like another?")
break
_______________________________________________________
When I look at this SO question it splits the votes half choose try except the other conditional logic, neither are wrong but which is the more obvious python way. https://stackoverflow.com/questions/2020598/in-python-how-should-i-test-if-a-variable-is-none-true-or-false
_______________________________________________________
I actually thought this would have resolved my issues and still returned error if ints entered however it still passes through.
answer = input("\t >> ")
if isinstance(answer, str) is True:
print(v0 * t - 0.5 * g * t ** 2)
elif int(answer) is True:
raise ValueError("Ints aren't valid input")
sys.exit()
else:
print("Ok please ammend your entries")
Thanks
Sayth
More information about the Python-list
mailing list