我有这个功能:
def int_input(promt):
while True:
try:
int(promt)
except ValueError:
print "Not a number, try again."
promt = raw_input("Enter your choice:")
我希望它在某些时候突破,如果它是一个数字,则返回 promt ,而我似乎无法找到合理的方法。
答案 0 :(得分:4)
不是100%肯定你还在做什么,但是如果你这样做,它就会在你输入一个有效的int之后才会返回。
def int_input():
while True:
try:
return int(raw_input("Enter your choice:"))
except ValueError:
print "Not a number, try again."
print int_input()
输出
Enter your choice: asdf
Not a number, try again.
Enter your choice: 2df
Not a number, try again.
Enter your choice: 3
3
答案 1 :(得分:0)
这是否符合您的要求:
def int_input(promt):
while True:
try:
int(promt)
except ValueError:
print "Not a number, try again."
promt = raw_input("Enter your choice:")
continue
return int(promt)
答案 2 :(得分:0)
try
.. except
有一个可选的else
子句:
def int_input(promt):
while True:
try:
int(promt)
except ValueError:
print "Not a number, try again."
promt = raw_input("Enter your choice:")
else: # no exception occured, we are safe to leave this loop
break # or return, or whatever you want to do...
但这不是必要的,你可以只在return
内部break
或try
(在int()演员之后。只有在没有例外时才会到达在int()
)期间。
答案 3 :(得分:0)
Ngenator的答案有点清晰,但您可以将变量设置为开关,以表明您获得了正确的值:
def int_input(promt): got_int = False while not got_int: try: int(promt) got_int = True except ValueError: print "Not a number, try again." promt = raw_input("Enter your choice:")