Kim Jinung

Python - for/else 본문

Language/Python

Python - for/else

Kim Jinung 2022. 12. 2. 18:36
 

4. More Control Flow Tools — Python 3.11.0 documentation

4. More Control Flow Tools Besides the while statement just introduced, Python uses the usual flow control statements known from other languages, with some twists. 4.1. if Statements Perhaps the most well-known statement type is the if statement. For examp

docs.python.org


for loop 순회 중 특정 조건을 찾고 break를 걸어야하는 일이 있다. 그리고 break 조건에 해당하는 케이스를 찾지 못하는 경우 마지막에 추가 if state를 붙여서 후처리를 하는 패턴을 줄곧 사용해왔다. 그런데 이를 조금 더 우아하게 처리할 수 있는 for/else 패턴이 존재한다. 

 

 

예제는 다음과 같다.

my_list = [1, 3, 5]

for num in my_list:
	print(num)
else:
	print("Yaho!")

my_list의 포함되어 있는 각 요소를 출력한다. 그런데 여기서는 어떠한 경우에도 Yaho! 를 출력할 수 없다. break를 걸어주는 조건이 없기 때문이다.

 

 

 

다시 다음 예제를 보면,

for num in my_list:
	if num % 2 != 0:
    		break
else:
	print("Not caught")

my_list의 인자가 홀수일 때 루프는 종료된다. 그러므로 Yaho는 출력되지 않는다.

 

 

 

마지막 예제를 살펴보면,

for num in my_list:
	if num % 2 == 0:
    		break
else:
	print("Not caught")

my_list에는 짝수가 없기 때문에 모든 루프를 순회 하여도 break 조건을 걸 수 없다.

따라서 마지막 else 문에서 Not caught를 출력한다.

 

'Language > Python' 카테고리의 다른 글

Python - heapq  (0) 2022.12.08
Python - Counter  (0) 2022.12.06
Python - Regular Expression  (0) 2022.11.30
Python - GIL(Global Interpreter Lock)  (0) 2022.11.23
Python - container, iterable, iterator, generator  (0) 2022.11.22