[SK shiedlus Rookies 23]Python(2-1)_24.10.16

박소민·2024년 10월 22일

Python

목록 보기
4/23

제어문

: 반복문의 실행 흐름을 제어하기 위한 키워드

  • break 문 : 실행 중인 반복문 즉시 종료
<<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
  • continue 문 : 현재 실행중인 반복문의 특정 부분 건너뛰고 다음 반복 계속 진행
<<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='')
  • pass 문 : 아무런 동작도 하지 않는 문장
    -EX> 1. 함수나 클래스를 미리 정의하고 구현은 나중에 할 때
             ⤷ 구현되지 않은 부분 표시 + 코드구조 잡아주기
    1. 조건문/반복문에서 아무 것도 하지 않고 넘길 때
<<def 함수>>
def my_func():   # 함수 선언부
    pass         # 함수 구현부 => 아무것도 하지 않는다

<<반복/조건문>>
for i in range(1,11):
    if i %2 == 0:
        pass
    else:
        print(i)     #1 3 5 7 9
  • else 문
    : 조건/반복문에서 조건이 충족되지 않거나 반복이 정상적으로 완료되었을 때 실행되는 코드 블록
<<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

컴프리헨션 (comprehension)

리스트 컴프리헨션(list comprehension)

: 반복/조건문을 간결 + 효율적인 방식으로 한 줄로 표현된 새로운 리스트를 생성 문법
->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]

집합 컴프리헨션 (set comprehension)

: 중복된 요소를 제거하고, 유일한 값을 가지는 집합 생성

<<<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}

딕셔너리 컴프리헨션 (dictionary comprehension)

<<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}

0개의 댓글