![](/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.