Python - No valuerror on int with isalpha
为什么在此尝试/除非isalpha失败,否则不会引发valueerror。
我知道如果给定一个数字,isalpha会返回false
1 2 3 4 5 | In [9]: ans = input("Enter a Letter") Enter a Letter4 In [10]: ans.isalpha() Out[10]: False |
如果它们提供的是数字而不是Y或N,我如何得到值错误?因为如果尝试是错误的,难道它不应该停止是真的而不打印我的轨迹吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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,则仍会得到答案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $ 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? |
有关错误的示例,请参阅
在您的情况下,只需测试:
1 2 3 4 | answer = input("\t >>") if answer.isalpha(): print(v0 * t - 0.5 * g * t ** 2) break |
一般来说,您应该更喜欢使用正常的控制流逻辑来处理一系列用户输入,而不是引发/捕获异常。
你需要自己提出错误。输入您不喜欢的内容不会引发异常:
1 2 3 4 5 6 7 8 | 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() |
为了清晰起见,我发布了一个答案,试图提供一种更加一致和明确的方法来处理字符串和int。通过使用isInstance,我向一个明确阅读我的代码的人声明我的值将有望提高可读性。
1 2 3 4 5 6 7 8 | 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允许对多种类型进行检查,从而增加了灵活性。
参考如何正确使用python的isInstance()检查变量是否为数字?
1 2 3 | def testSomething(arg1, **types): if isintance(arg1, [types]): do_something |