這個問題在這里已經有了答案: 如何跳出多個回圈? (32 個回答) 4 天前關閉。
我在下面的代碼中簡化了我的回圈問題:
所以,我有一個myfunction()包含很多步驟的函式。
這個函式是通過使用回圈(第 28 到 30 行)來執行的,對于 range(0,4) -> 執行我的函式
我的函式中的步驟總結了兩種情況:
- 第一種情況:如果步驟正確:
print('correct')然后轉到下一個范圍 - 第二種情況:如果步驟不正確:
print('incorrect')并重新運行該功能
問題發生在第二種情況下,當它運行該函式時它不正確,然后當它從第 17 行重新運行該函式然后它正確時,我希望它在那之后打破所有回圈并轉到下一個范圍
執行我的腳本并測驗 2 個案例以了解更多我的問題:
正確情況:第一個輸入 = 1,第二個輸入 = 1
不正確的情況:第一個輸入 = 1,第二個輸入 = p,當它從第 17 行重新運行時:第一個輸入 = 1,第二個輸入 = 1
# Correct case : first input = 1 , second input = 1
# Incorrect case : first input = 1 , second input = p
def myfunction():
user_action = int(input('Enter number 1: '))
try:
user_action2 = int(input('Enter '))
x = user_action user_action2
print('correct')
pass
except:
print('incorrect')
while True:
left = 5
if left == 5:
print("repeat")
myfunction()
# Here should break all the loops and go back to line 29 for the next number range
break
else:
continue
pass
print('this should not be printed twice in case of incorrect results')
for y in range(0,4):
print(y)
myfunction()
# The issue happens when it's an Incorrect case : first input = 1 , second input = p and when it re runs from line 17, make it correct first input = 1 , second input = 1
uj5u.com熱心網友回復:
我認為您需要的是使用 areturn而不是 a break:
user_action = int(input('Enter number 1: '))
try:
user_action2 = int(input('Enter '))
x = user_action user_action2
print('correct')
pass
except:
print('incorrect')
while True:
left = 5
if left == 5:
print("repeat")
myfunction()
#right here
return
else:
continue
pass
print('this should not be printed twice in case of incorrect results')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362964.html
