for 루프

개발자를 위한 Python 입문

Jasmin Ludolf

Senior Data Science Content Developer

개별 비교

# Ingredient quantities
quantities = [500, 400, 15, 20, 30, 5]
# Validate values
quantities[0] < 10
False
quantities[1] < 10
False
개발자를 위한 Python 입문

for 루프 구문

for value in sequence:
    action
  • sequence의 각 value에 대해 (for) 이 action을 수행

    • action은 이전 줄의 콜론 때문에 들여쓰기되어 있습니다
  • sequence = 반복 가능한 객체(예: 리스트, 딕셔너리 등)

  • value = 반복자(즉, 인덱스)
    • 자리표시자(이름은 무엇이든 가능), i는 일반적
개발자를 위한 Python 입문

개별 값 출력

# Ingredients list
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]


# Loop through and print each ingredient for ingredient in ingredients:
print(ingredient)
pasta
tomatoes
garlic
basil
olive oil
salt
개발자를 위한 Python 입문

for 루프의 조건문

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:
개발자를 위한 Python 입문

for 루프의 조건문

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:

# Check if quantity is more than 500 if qty > 500: print("Plenty in stock") elif qty >= 100: print("Enough for a small portion") else: print("Nearly out!")
개발자를 위한 Python 입문

for 루프의 조건문

Plenty in stock
Enough for small
Nearly out!
Nearly out!
Nearly out!
개발자를 위한 Python 입문

문자열 순환하기

ingredient_name = "pasta"

# Loop through each character for letter in ingredient_name: print(letter)
p
a
s
t
a
  • 텍스트 검증, 특수 문자 확인에 유용
개발자를 위한 Python 입문

딕셔너리 순환하기

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}

# Loop through keys and values for item, qty in ingredients.items(): print(item, ":", qty, "grams")
pasta : 500 grams
tomatoes : 400 grams
garlic : 30 grams
  • item = 키(재료 이름)
  • qty = 값(수량)
개발자를 위한 Python 입문

딕셔너리 순환하기

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}
factor = 2

# Calculate scaled quantities for item, qty in ingredients.items(): scaled_qty = qty * factor print(item, ":", scaled_qty, "grams")
pasta : 1000 grams
tomatoes : 800 grams
garlic : 60 grams
개발자를 위한 Python 입문

딕셔너리 순환하기

# Loop through keys only
for item in ingredients.keys():
    print(item)
pasta
tomatoes
garlic
# Loop through values only
for qty in ingredients.values():
    print(qty, "grams")
500 grams
400 grams
30 grams
개발자를 위한 Python 입문

범위

range(start, end + 1)
  • start = 시작 숫자
  • end = 끝 숫자
  • 값을 생성하거나 수정하는 데 사용됨
for i in range(1, 6):
    print(i)
1
2
3
4
5
개발자를 위한 Python 입문

연습해 봅시다!

개발자를 위한 Python 입문

Preparing Video For Download...