![](/img/trans.png)
[英]how to make continue function in python goes back to a specific line inside the loop, not through the entire loop
[英]Continue statement in Python only goes back at start of the loop. How to make it go in any place of code?
我有这个简单的代码:
var = 1
while var == 1 :
try:
num = int(raw_input("Enter a number :"))
except ValueError:
print "Thats not a number!"
continue
try:
num2 = int(raw_input("Enter another number :"))
except ValueError:
print "Thats not a number!"
continue
print "Sum of previous 2 inputs:="+str(num+num2)
print "Good bye!"
现在,第一个继续语句可以完成工作,而第二个则不能。 因为它返回循环的顶部,但是我需要它返回捕获到第二个异常的位置,因此它将要求再次输入第二个数字,而不是第一个数字。
有任何想法吗?
您可以排除在函数中输入数字的麻烦–这样可以避免重复编写相同的代码两次:
def input_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
print "That's not a valid integer!"
...
num = input_int("Please enter a number: ")
num2 = input_int("Please enter another number: ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.