try except 블록 (for 루프 내부) 내부의 코드 블록이 성공적으로 실행되고 예외를 호출하지 않는 경우이 for 루프에서 벗어나는 방법을 찾으려고합니다 .
나를 위해 작동하지 않는 코드는 다음과 같습니다.
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
break
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
이 성공적으로 실행 된 J15
후에도 시도 목록 내의 항목을 계속 호출하고 있기 때문입니다.I15
여기에 코드 :
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
코드가 이미 전체 attempt
를 시도한 경우 실제 예외를 throw하는 데 사용됩니다 .attempts
for … else
개념 이 필요합니다 : https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
except KeyError:
# error, let's try another item from attempts
continue
else:
# success, let's get out of the loop
break
else:
# this happens at the end of the loop if there is no break
raise KeyError
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다