为什么在此try /上没有引发ValueError,除非isalpha失败。
我知道如果给出一个数字,isalpha会返回false
In [9]: ans = input("Enter a Letter")
Enter a Letter4
In [10]: ans.isalpha()
Out[10]: False
如果提供数字而不是y或n,我如何得到值错误?因为如果尝试是假的,它不应该停止是真的而不是打印我的轨迹吗?
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.answer)
sys.exit()
finally:
print("would you like another?")
break
例如,如果用户键入5而不是y或n仍然得到答案
$ python3 ball.py
What velocity would you like? 2
What gravity would you like? 3
What time decimal would you like? 4
We have the following inputs.
v0 is 2
g is 3
t is 4
Is this correct? [Y/n]
>> 5
-16.0
would you like another?
答案 0 :(得分:3)
except ValueError as err:
。 answer
的值为False
,但这只是一个任意的布尔值,而不是错误。
有关错误的示例,请参阅{{3}}。
在您的情况下,只需测试:
answer = input("\t >> ")
if answer.isalpha():
print(v0 * t - 0.5 * g * t ** 2)
break
答案 1 :(得分:2)
通常,您应该更喜欢使用普通的控制流逻辑来处理一系列用户输入,而不是提出/捕获异常。
答案 2 :(得分:1)
您需要自己提出错误。键入您不喜欢的内容不会引发异常:
try:
answer = input("\t >> ").isalpha()
if not answer:
raise ValueError
print(v0 * t - 0.5 * g * t ** 2)
except ValueError as err:
print("Not a valid entry", err.answer)
sys.exit()
答案 3 :(得分:0)
通过对字符串和 int的的处理,提供一种更加一致和明确的方法,以便清晰地发布答案。通过使用 isinstance ,我向明确阅读我的代码的人宣告我的价值观有望提高可读性。
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")
如果我以后有不同的要求,可以很容易地将其抽象为一个函数,因为isinstance允许检查多种类型增加灵活性。
参考 How to properly use python's isinstance() to check if a variable is a number?
def testSomething(arg1, **types):
if isintance(arg1, [types]):
do_something