我正在尝试支持用户输入文件名的重复,然后输入两个整数。因此,如果抛出异常,我希望再次提示用户输入。
我的问题是如果输入了一个有效的文件但是输入了一个无效的整数,它将再次请求该文件,而不仅仅是整数。如何修复代码,以便再次请求整数。
这就是我所拥有的:
while True:
try:
f = raw_input("Enter name of file: ")
inFile = open(f)
# more code
except IOError:
print ("The file does not exist. Try Again.")
else:
try:
integer = int(raw_input("Enter an integer: "))
integer2 = int(raw_input("Enter an integer: "))
# more code
except (TypeError, ValueError):
print ("Not an integer. Try Again.")
答案 0 :(得分:9)
尝试使用多个while
循环:
while True:
fileName = raw_input("Enter name of file: ")
try:
# more code here to detect or open the file
break
except Exception: # can be IOError or something else
print ("error msg")
while True:
try:
integer = int(raw_input("Enter an integer: "))
integer2 = int(raw_input("Enter an integer: "))
break
except (TypeError, ValueError):
print ("error msg")
# more code
答案 1 :(得分:0)
while True:
try:
a = int(raw_input('a: '))
b = int(raw_input('b: '))
break
except ValueError:
print "Numbers idiot"
#more code here
此代码将跳转到a或b上的except块,如果数字有效,则继续使用更多代码。
答案 2 :(得分:0)
>>> def ask(question, func, exceptions):
... while True:
... try:
... return func(raw_input(question))
... except exceptions, error:
... pass
...
>>> x = ask("integer?", int, ValueError)
integer?o
integer?l
integer?42
>>> x
42
答案 3 :(得分:0)
为了扩展上面关于使用多个while循环的答案以及有关处理其他数据验证的相关问题而不必循环已经验证的数据,以下内容看起来很狡猾,但它为您提供了您希望实现的粒度检查:
while True:
fileName = raw_input("Enter name of file: ")
try:
# more code here to detect or open the file
break
except Exception:
print ("The file does not exist. Try Again.")
while True:
try:
integer = int(raw_input("Enter an integer: "))
break
except (TypeError, ValueError):
print ("Not an integer. Try Again.")
while True:
try:
integer2 = int(raw_input("Enter an integer: "))
break
except(TypeError, ValueError):
print ("Not an integer. Try Again.")