루프

루프 에서 Python

93개의 연습 문제

루프 소개

Python에는 두 가지 반복 구조가 있어요. 불확정(횟수를 세지 않는) 반복을 위한 while 루프와 확정(횟수를 세는) 반복을 위한 for 루프예요. break, continue, else 키워드는 루프 동작을 바꾸는 데 도움을 줘요. range()와 enumerate()는 반복 횟수를 세고 인덱스를 다루는 데 도움을 줘요.

While

while 루프는 loop expression 또는 "test"가 boolean context에서 True로 평가되는 동안 계속 실행되다가, False로 평가되면 끝나요:

# Lists are considered "truthy" in a boolean context if they
# contain one or more values, and "falsy" if they are empty.

>>> placeholders = ["spam", "ham", "eggs", "green_spam", "green_ham", "green_eggs"]

>>> while placeholders:
...     print(placeholders.pop(0))
...
'spam'
'ham'
'eggs'
'green_spam'
'green_ham'
'green_eggs'

For

Python의 기본 for loop는 for each라고 하는 편이 더 정확한데, 어떤 이터러블 객체의 값들을 차례로 돌면서 next()를 호출해도 더 이상 값이 반환되지 않을 때(StopIteration을 발생시킬 때) 끝나요.

>>> word_list = ["bird", "chicken", "barrel", "bongo"]

>>> for word in word_list:
...    if word.startswith("b"):
...        print(f"{word.title()} starts with a B.")
...    else:
...        print(f"{word.title()} doesn't start with a B.")
...
'Bird starts with a B.'
'Chicken doesn\'t start with a B.'
'Barrel starts with a B.'
'Bongo starts with a B.'

시퀀스 객체 range()

딱히 주어진 iterable이 없을 때는 특별한 range() 시퀀스가 반복 카운터로 쓰여요. range()는 시퀀스를 stop할 지점 앞의 int가 필요하고, 선택적으로 start와 step 매개변수를 받을 수 있어요. start 숫자를 주지 않으면 시퀀스는 0부터 시작해요. range() 객체는 lazy(값이 요청될 때 생성돼요)하고, 모든 공통 시퀀스 연산을 지원하며, 지정한 시퀀스가 아무리 길어도 고정된 양의 메모리만 차지해요. 흥미롭게도 range()는 반복자가 아니에요. 숫자 시퀀스가 필요한, 반복과는 무관한 여러 상황에서도 쓸 수 있어요.

# Here we use range to produce some numbers, rather than creating a list of them in memory.
# The values will start with 1 and stop *before* 7.

>>> for number in range(1, 7):
...    if number % 2 == 0:
...       print(f"{number} is even.")
...    else:
...       print(f"{number} is odd.")
'1 is odd.'
'2 is even.'
'3 is odd.'
'4 is even.'
'5 is odd.'
'6 is even.'

# range() can also take a *step* parameter.
# Here we use range to produce only the "odd" numbers, starting with 3 and stopping *before* 15.

>>> for number in range(3, 15, 2):
...    if number % 2 == 0:
...       print(f"{number} is even.")
...    else:
...       print(f"{number} is odd.")
...
'3 is odd.'
'5 is odd.'
'7 is odd.'
'9 is odd.'
'11 is odd.'
'13 is odd.'

enumerate()로 값과 인덱스 얻기

값과 인덱스가 둘 다 필요하면, 내장 enumerate(<iterable>)가 (index, value) 쌍을 넘겨주는 iterator를 반환해요:

>>> word_list = ["bird", "chicken", "barrel", "apple"]

# *index* and *word* are the loop variables.
# Loop variables can be any valid python name.

>>> for index, word in enumerate(word_list):
...    if word.startswith("b"):
...        print(f"{word.title()} (at index {index}) starts with a B.")
...    else:
...        print(f"{word.title()} (at index {index}) doesn't start with a B.")
...
'Bird (at index 0) starts with a B.'
'Chicken (at index 1) doesn\'t start with a B.'
'Barrel (at index 2) starts with a B.'
'Apple (at index 3) doesn\'t start with a B.'


# The same method can be used as a "lookup" for pairing items between two lists.
# Of course, if the lengths or indexes don't line up, this doesn't work.

>>> word_list = ["cat", "chicken", "barrel", "apple", "spinach"]
>>> category_list = ["mammal", "bird", "thing", "fruit", "vegetable"]

>>> for index, word in enumerate(word_list):
...    print(f"{word.title()} is in category: {category_list[index]}.")
...
'Cat is in category: mammal.'
'Chicken is in category: bird.'
'Barrel is in category: thing.'
'Apple is in category: fruit.'
'Spinach is in category: vegetable.'

enumerate(<iterable>) 함수는 인덱스 세기를 다른 숫자에서 start하도록 지정할 수도 있어요:

# Here, the index count will start at 1.
>>> for position, word in enumerate(word_list, start=1):
...    if word.startswith("b"):
...        print(f"{word.title()} (at position {position}) starts with a B.")
...    else:
...        print(f"{word.title()} (at position {position}) doesn't start with a B.")
...
'Bird (at position 1) starts with a B.'
'Chicken (at position 2) doesn\'t start with a B.'
'Barrel (at position 3) starts with a B.'
'Apple (at position 4) doesn\'t start with a B.'

반복 동작 바꾸기

continue 키워드를 쓰면 다음 반복 주기로 건너뛸 수 있어요:

>>> word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple", "bear"]
...
... # This will skip *bird*, at index 0
... for index, word in enumerate(word_list):
...     if index == 0:
...         continue
...     if word.startswith("b"):
...         print(f"{word.title()} (at index {index}) starts with a b.")
...
'Barrel (at index 2) starts with a b.'
'Bongo (at index 3) starts with a b.'
'Bear (at index 6) starts with a b.'

break 키워드(많은 C 계열 언어에서처럼)를 쓰면 반복을 멈추고 가장 안쪽의 바깥 loop에서 "빠져나올" 수 있어요:

>>>  word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple"]

>>> for index, word in enumerate(word_list):
...    if word.startswith("b"):
...        print(f"{word.title()} (at index {index}) starts with a B.")
...    elif word == "sliver":
...        break
...    else:
...        print(f"{word.title()} doesn't start with a B.")
... print("loop broken.")
...
'Bird (at index 0) starts with a B.'
'Chicken doesn\'t start with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'loop broken.'

루프 else 절은 Python에만 있는 것으로, 반복이 다 끝났을 때 "마무리"하거나 "결론짓는" 동작에 쓸 수 있어요. else 키워드 뒤의 문장은 반복이 break로 끝나면 실행되지 않아요:

>>> word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple"]

# Using enumerate to get both an index and a value.

>>> for index, word in enumerate(word_list):
...    word = word.title()
...    if word.startswith("B"):
...        print(f"{word} (at index {index}) starts with a B.")
...
... # This executes once *StopIteration* is raised and 
... # There are no more items to iterate through.
... # Note the indentation, which lines up with the for keyword.
... else:
...    print(f"Found the above b-words, out of {len(word_list)} words in the word list.")
...
'Bird (at index 0) starts with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'Found the above b-words, out of 6 words in the word list.'


# Terminating a loop via *break* will bypass the loop *else* clause

>>> for index, word in enumerate(word_list):
...    word = word.title()
...    if word.startswith("B"):
...       print(f"{word} (at index {index}) starts with a B.")
...    if word.startswith("S"):
...        print("Found an S, stopping iteration.")
...        break

... # This statement does not run, because a *break* was triggered.
... else:
...    print(f"Found the above b-words, out of {len(word_list)} words in the word list.")
...
'Bird (at index 0) starts with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'Found an S, stopping iteration.'
GitHub에서 편집 링크가 새 창이나 탭에서 열려요

루프 배우기

연습이 잠겨 있어요

루프 개념을 연습하려면 연습 문제 6개를 더 잠금 해제해요