Python 3.4中ValueError未被触发
好的,我现在想要做的就是防止有人在这个输入框里输入字符串。
#User selection
print("Which program would you like to run?")
print("(Type '9' if you wish to exit the menu)")
selection = int(input())
print()
#Security statement followed by case statement
while selection <= 0 or selection >= 10:
try:
print("That is an invalid selection, please input a proper selection.")
print("Which program would you like to run?")
selection = int(input())
print()
except ValueError:
print("Cmon man")
简单来说,我的代码没有运行。我试着把所有东西重新整理了一遍,但还是没找到合适的解决办法。我已经找了快一个小时了,还是没有任何帮助。有好心人吗?
顺便说一下,那个case语句的部分我还没写。
附言:我一直收到的都是“字符串不是数字”的常见错误提示。
(“ValueError: invalid literal for int() with base 10: 'why'”)
再附言:问题已经被指出了。看来我真的是傻傻的没注意到,哈哈... 感谢大家的帮助。
1 个回答
0
你的 try...except
代码没有包含用户最开始的输入,所以 ValueError
这个错误其实没有被捕捉到。如果你输入一个不在规定范围内的整数(也就是小于0或者大于10)作为第一个输入,你就能看到 try...except
的效果了。
你需要调整一下你的代码,把第一次输入的请求放到 try
块里面,或者把现有的输入请求放到另一个 try...except
里面。
另外,顺便提一下,input()
可以接收一个字符串参数,这个字符串会作为提示信息显示给用户。
selection = int(input("Which program would you like to run? "))