코드 실행 흐름을 한 단계씩 눈으로 확인하세요
정해진 개수만큼 반복해요!
for 변수 in 수열: — 마치 상자에서 하나씩 꺼내듯이, 수열의 각 값을 변수에 넣으며 반복합니다! range(3)이면 0, 1, 2 세 번 반복해요.
for i in range(3): print(i)n = 4for i in range(1, n + 1): print(i)t = "hello python world".split()for s in t: print(s)fruits = ["딸기", "포도", "오렌지"]for fruit in fruits: print(fruit)for i in range(1, 10): print(f"2 x {i} = {2 * i}")조건이 맞는 동안 계속 반복해요!
while 조건식: — 조건이 참(True)인 동안 계속 반복하고, 거짓(False)이 되면 멈춰요. break는 즉시 탈출, continue는 건너뛰고 다음 반복으로!
n = 1while n <= 3: print(n) n = n + 1arr = [5, 3, 8, -1]i = 0while i < len(arr): if arr[i] < 0: break print(arr[i]) i = i + 1i = 1while i <= 7: if i % 3 == 0: i = i + 1 continue print(i) i = i + 1total = 0i = 1while i <= 10: if i % 2 == 0: total += i i += 1print("짝수 합계:", total)반복 속에 또 다른 반복이 있어요!
for문이나 while문을 다른 반복문 안에 넣을 수 있어요. 마치 상자 안에 또 다른 상자가 있는 것처럼! 이렇게 하면 복잡한 패턴을 만들 수 있어요.
for i in range(1, 5): for j in range(i): print("*", end="") print("")for i in range(3): for j in range(4): print(i*4+j+1, end=" ") print("")for i in range(5, 0, -1): print("*" * i)반복문으로 실제 문제를 풀어봐요!
반복문은 여러 데이터를 처리하거나, 어떤 조건을 만족할 때까지 계산하는데 정말 유용해요! 합계를 구하거나, 조건을 확인하거나, 패턴을 찾을 때 많이 쓰인답니다.
total = 0for i in range(1, 6): total = total + iprint(total)n = 7is_prime = Truefor i in range(2, n): if n % i == 0: is_prime = Falseprint(is_prime)secret = 5attempts = 0while attempts < 3: guess = int(input("추측: ")) if guess == secret: print("정답!"); break elif guess < secret: print("더 높은 수를 입력하세요.") else: print("더 낮은 수를 입력하세요.") attempts += 1