python의 for문에 대해 설명해줘.
**for ~ in**은 Python에서 가장 많이 쓰는 반복문이에요!
기본 문법:
for 변수 in 반복가능한것:
실행할 코드
다양한 사용 방법:
1. 리스트 반복
fruits = ["사과", "바나나", "오렌지"]
for fruit in fruits:
print(fruit)
# 출력:
# 사과
# 바나나
# 오렌지
2. 문자열 반복
word = "Python"
for letter in word:
print(letter)
# 출력:
# P
# y
# t
# h
# o
# n
3. 숫자 범위 반복 (range)
# 0부터 4까지
for i in range(5):
print(i)
# 출력: 0, 1, 2, 3, 4
# 1부터 5까지
for i in range(1, 6):
print(i)
# 출력: 1, 2, 3, 4, 5
# 2씩 증가
for i in range(0, 10, 2):
print(i)
# 출력: 0, 2, 4, 6, 8
4. 딕셔너리 반복
student = {"이름": "김철수", "나이": 20, "학과": "컴퓨터"}
# 키만 반복
for key in student:
print(key)
# 키와 값 둘 다 반복
for key, value in student.items():
print(f"{key}: {value}")
# 출력:
# 이름: 김철수
# 나이: 20
# 학과: 컴퓨터
실용적인 예시들:
1. 리스트의 합계 구하기
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"합계: {total}") # 출력: 합계: 15
2. 조건문과 함께 사용
scores = [85, 92, 78, 96, 88]
for score in scores:
if score >= 90:
print(f"{score}점: 우수")
elif score >= 80:
print(f"{score}점: 양호")
else:
print(f"{score}점: 보통")
3. 인덱스와 함께 반복 (enumerate)
colors = ["빨강", "파랑", "노랑"]
for index, color in enumerate(colors):
print(f"{index}: {color}")
# 출력:
# 0: 빨강
# 1: 파랑
# 2: 노랑
4. 여러 리스트 동시에 반복 (zip)
names = ["김철수", "이영희", "박민수"]
ages = [20, 22, 21]
for name, age in zip(names, ages):
print(f"{name}는 {age}살")
# 출력:
# 김철수는 20살
# 이영희는 22살
# 박민수는 21살
고급 기법들:
1. 리스트 컴프리헨션
# 일반 for문
squares = []
for i in range(5):
squares.append(i ** 2)
# 리스트 컴프리헨션 (한 줄로!)
squares = [i ** 2 for i in range(5)]
print(squares) # [0, 1, 4, 9, 16]
2. 조건부 리스트 컴프리헨션
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 짝수만 선택
evens = [num for num in numbers if num % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
3. 중첩 반복문
# 구구단 만들기
for i in range(2, 10): # 2단부터 9단까지
print(f"=== {i}단 ===")
for j in range(1, 10): # 1부터 9까지
print(f"{i} × {j} = {i * j}")
break와 continue:
break (반복 중단)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in numbers:
if num == 5:
break # 5를 만나면 반복 종료
print(num)
# 출력: 1, 2, 3, 4
continue (다음 반복으로)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in numbers:
if num % 2 == 0: # 짝수면
continue # 스킵하고 다음으로
print(num)
# 출력: 1, 3, 5, 7, 9 (홀수만)
실전 활용 예시:
파일 처리
with open('data.txt', 'r') as file:
for line in file:
print(line.strip()) # 각 줄 출력
웹 크롤링
urls = ['https://site1.com', 'https://site2.com', 'https://site3.com']
for url in urls:
# 각 URL에서 데이터 수집
print(f"Processing {url}")
요약:
for ~ in = "이것들을 하나씩 꺼내서 반복해줘!" 🔄
- 리스트, 문자열, 딕셔너리 등 모든 반복 가능한 객체와 사용
- range() 함수로 숫자 범위 반복
- enumerate(), zip() 등으로 고급 반복
- break, continue로 흐름 제어
- 리스트 컴프리헨션으로 간결하게 작성
Python 프로그래밍의 핵심 문법 중 하나예요!
딕셔녀리 반복에서 값만 반복할 수도 있어?
네, 가능해요! 딕셔너리에서 값만 반복하는 방법이 있어요.
값만 반복하는 방법:
.values() 사용
student = {"이름": "김철수", "나이": 20, "학과": "컴퓨터"}
# 값만 반복
for value in student.values():
print(value)
# 출력:
# 김철수
# 20
# 컴퓨터
딕셔너리 반복의 모든 방법:
1. 키만 반복 (기본)
student = {"이름": "김철수", "나이": 20, "학과": "컴퓨터"}
for key in student: # 또는 student.keys()
print(key)
# 출력:
# 이름
# 나이
# 학과
2. 값만 반복
for value in student.values():
print(value)
# 출력:
# 김철수
# 20
# 컴퓨터
3. 키와 값 둘 다 반복
for key, value in student.items():
print(f"{key}: {value}")
# 출력:
# 이름: 김철수
# 나이: 20
# 학과: 컴퓨터
실용적인 예시들:
점수만 계산하기
scores = {"수학": 85, "영어": 92, "과학": 78}
# 점수만 반복해서 평균 계산
total = 0
for score in scores.values():
total += score
average = total / len(scores)
print(f"평균 점수: {average}") # 평균 점수: 85.0
이름만 출력하기
users = {
"user1": "김철수",
"user2": "이영희",
"user3": "박민수"
}
print("사용자 목록:")
for name in users.values():
print(f"- {name}")
# 출력:
# 사용자 목록:
# - 김철수
# - 이영희
# - 박민수
값들로 새 리스트 만들기
product_prices = {
"사과": 1000,
"바나나": 1500,
"오렌지": 2000
}
# 가격만 모아서 리스트로
prices = []
for price in product_prices.values():
prices.append(price)
print(prices) # [1000, 1500, 2000]
# 또는 리스트 컴프리헨션으로
prices = [price for price in product_prices.values()]
조건부 값 필터링
inventory = {
"사과": 50,
"바나나": 5, # 재고 부족
"오렌지": 30,
"포도": 3 # 재고 부족
}
print("재고 부족 상품들:")
for product, quantity in inventory.items():
if quantity < 10: # 값을 조건으로 사용
print(f"- {product}: {quantity}개")
# 값만 사용해서 총 재고 계산
total_stock = sum(inventory.values())
print(f"총 재고: {total_stock}개")
리스트 컴프리헨션으로도 가능:
scores = {"수학": 85, "영어": 92, "과학": 78}
# 80점 이상인 점수들만
high_scores = [score for score in scores.values() if score >= 80]
print(high_scores) # [85, 92]
# 모든 점수에 5점 추가
bonus_scores = [score + 5 for score in scores.values()]
print(bonus_scores) # [90, 97, 83]
요약:
방법 코드 결과
키만 | for key in dict: | 키들만 반복 |
키만 | for key in dict.keys(): | 키들만 반복 |
값만 | for value in dict.values(): | 값들만 반복 ✅ |
키+값 | for key, value in dict.items(): | 키와 값 둘 다 |
.values() 메서드를 사용하면 딕셔너리의 값만 깔끔하게 반복할 수 있어요! 🎯
'note' 카테고리의 다른 글
python의 모듈 (1) | 2025.09.17 |
---|---|
언패킹 (0) | 2025.09.16 |
response = client.chat.completions.create() (1) | 2025.09.15 |
패키지와 라이브러리의 차이. (1) | 2025.09.14 |
bash, zsh, venv, Django, UV, pip (0) | 2025.09.14 |