: 반복문의 실행 흐름을 제어하기 위한 키워드
<<1. for문>>
for i in range(5):
print(i, end=' ') # 0 1 2 3 4
for i in range(5):
if i == 3:
break ⚡
print(i, end=' ') # 0 1 2
<<2. while문>>
n = 1
while True:
if n > 10:
break ⚡
print(n) # 0 1 2 3 4 5 6 7 8 9 10
n += 1
<<3. 중첩 반복문>>
for i in range(3):
for j in range(3):
if j == 1:
break ❓반복문 내부만 종료(off), 외부는 실행(on)
print(f'i: {i}, j: {j}') #i: 0, j: 0
#i: 1, j: 0
#i: 2, j: 0
건너뛰고 다음 반복 계속 진행<<1>>
for i in range(3):
if i == 1: ❓i가 1 일때 continue
continue
print(i, end=' ') # 0 2
<<2>>
for i in range(1,11):
if i % 2 == 0: ❓i가 짝수 일때 continue
continue
print(i) # 1 3 5 7 9
<<3>>
user_input = input('메시지를 입력하세요: ')
for c in user_input:
if c == ',' or c == '!' or c == '?':
continue ⤷ ❓입력 메시지에서 (,), (?), (!)를 제외한 나머지 문자 출력
print(c, end='')
⤷ 구현되지 않은 부분 표시 + 코드구조 잡아주기<<def 함수>>
def my_func(): # 함수 선언부
pass # 함수 구현부 => 아무것도 하지 않는다
<<반복/조건문>>
for i in range(1,11):
if i %2 == 0:
pass
else:
print(i) #1 3 5 7 9
<<1>>
for i in range(5):
print(i, end=' ')
else:
print("모두 출력되었습니다.") # 0 1 2 3 4 모두 출력되었습니다.
<<2>>
for i in range(5):
if i > 2:
break
print(i, end=' ')
else:
print("모두 출력되었습니다.") # 0 1 2
: 반복/조건문을 간결 + 효율적인 방식으로 한 줄로 표현된 새로운 리스트를 생성 문법
->so. 코드의 가독성을 높여줌

[표현식 for 항목 in 반복가능객체 if 조건문]<<1. for 반복문>>
numbers = []
for i in range(1, 11):
numbers.append(i)
print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
🔽
<<리스트 컴프리헨션>>
numbers = [i for i in range(1, 11)] ⚡
print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
--------------------------------------------------------
<<2. if 조건문>>
result = []
words = ['apple', 'banana', 'orange', 'melon', 'grape']
for word in words:
if len(word) <= 5: ❓글자 길이 <= 5
result.append(word)
print(result) # ['apple', 'melon', 'grape']
🔽
<<리스트 컴프리헨션>>
words = ['apple', 'banana', 'orange', 'melon', 'grape']
result = [ word for word in words if len(word) <= 5 ] ⚡
print(result) # ['apple', 'melon', 'grape']
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = []
for row in matrix:
for num in row:
flattened.append(num)
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
🔽
flattened = [num for row in matrix for num in row] ⚡
⤷ ❓이중 for문 사용 ➔ 내/외부 리스트의 모든 요소를 단일 리스트로 변환
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
: 중복된 요소를 제거하고, 유일한 값을 가지는 집합 생성
<<<list comprehension>>
new_list = [ x % 3 for x in range(10) ] ❓x를 3으로 나눈 나머지
print(new_list) # [0, 1, 2, 0, 1, 2, 0, 1, 2, 0]
🔽
<<set comprehension>>
new_set = { x % 3 for x in range(10) }
print(new_set) # {0, 1, 2}

<<dict. + for 반복문>>
dict_a = {}
for i in range(5):
if i**2 < 10:
dict_a[i] = i**2
print(dict_a) #{0: 0, 1: 1, 2: 4, 3: 9}
🔽
<<dict. comprehension>>
dict_a = {i:i**2 for i in range(5) if i**2 < 10}
print(dict_a) #{0: 0, 1: 1, 2: 4, 3: 9}
