Skip to Content
💻 코리아IT아카데미 신촌 - 프로그래밍 학습 자료

Topic 3: while 반복문 - 조건부 반복 🔄

🎯 학습 목표

while 반복문의 구조와 동작 원리를 이해하고, 조건에 따라 코드를 반복 실행할 수 있으며, 무한루프를 방지하는 방법을 알 수 있습니다.

🔄 반복문의 필요성

반복 작업의 문제점

만약 1부터 10까지 출력하려면 어떻게 해야 할까요?

# 반복문 없이 하나씩 작성... print(1) print(2) print(3) print(4) print(5) print(6) print(7) print(8) print(9) print(10) # 너무 비효율적!

반복문의 해결책

# while 반복문 사용 count = 1 while count <= 10: print(count) count += 1 # 간단하고 효율적!

반복문을 사용하면 같은 작업을 간단하게 여러 번 수행할 수 있습니다.

🎯 while문 기본 구조

문법 구조

while 조건: 반복할 코드 조건 변경 코드

기본 예시

# 5번 인사하기 count = 1 while count <= 5: print(f"{count}번째 안녕하세요!") count += 1 print("인사 완료!")

while문의 동작 과정

  1. 조건 확인: 조건이 참(True)인지 확인
  2. 코드 실행: 조건이 참이면 반복할 코드 실행
  3. 조건 변경: 변수 값 변경 (중요!)
  4. 다시 1번으로: 조건 확인부터 반복

🔢 카운터 변수 활용

기본 카운터

# 1부터 5까지 출력 i = 1 while i <= 5: print(i) i += 1 # i = i + 1과 같음

역순 카운터

# 5부터 1까지 카운트다운 count = 5 while count > 0: print(f"카운트다운: {count}") count -= 1 print("발사!")

단계별 증가

# 2씩 증가하며 출력 number = 0 while number <= 10: print(number) number += 2 # 0, 2, 4, 6, 8, 10

💰 누적 계산

합계 계산

# 1부터 10까지의 합 total = 0 number = 1 while number <= 10: total += number # total = total + number number += 1 print(f"1부터 10까지의 합: {total}")

팩토리얼 계산

# 5! (5 팩토리얼) 계산 n = 5 factorial = 1 i = 1 while i <= n: factorial *= i # factorial = factorial * i i += 1 print(f"{n}! = {factorial}")

🎮 사용자 입력과 반복

올바른 입력 받기

# 양수가 입력될 때까지 반복 number = 0 while number <= 0: number = int(input("양수를 입력하세요: ")) if number <= 0: print("양수만 입력 가능합니다!") print(f"입력하신 양수: {number}")

메뉴 시스템

# 간단한 메뉴 시스템 choice = "" while choice != "q": print("\n=== 메뉴 ===") print("1. 인사하기") print("2. 계산하기") print("q. 종료") choice = input("선택: ") if choice == "1": print("안녕하세요!") elif choice == "2": a = int(input("첫 번째 숫자: ")) b = int(input("두 번째 숫자: ")) print(f"{a} + {b} = {a + b}") elif choice == "q": print("프로그램을 종료합니다.") else: print("잘못된 선택입니다.")

🛑 반복 제어: break와 continue

break - 반복문 탈출

# 특정 조건에서 반복 중단 count = 1 while count <= 10: if count == 5: break # 5가 되면 반복문 완전히 종료 print(count) count += 1 print("반복문 종료") # 출력: 1, 2, 3, 4, 반복문 종료

continue - 다음 반복으로 건너뛰기

# 짝수만 출력하기 number = 0 while number < 10: number += 1 if number % 2 == 1: # 홀수이면 continue # 아래 코드 건너뛰고 다음 반복으로 print(number) # 짝수만 출력됨 # 출력: 2, 4, 6, 8, 10

실용적인 활용

# 올바른 비밀번호 입력받기 correct_password = "python123" attempts = 0 max_attempts = 3 while attempts < max_attempts: password = input("비밀번호를 입력하세요: ") attempts += 1 if password == correct_password: print("로그인 성공!") break else: remaining = max_attempts - attempts if remaining > 0: print(f"틀렸습니다. {remaining}번 더 시도 가능합니다.") if attempts == max_attempts and password != correct_password: print("로그인 실패! 접근이 차단되었습니다.")

⚠️ 무한루프와 방지법

무한루프란?

조건이 절대 거짓이 되지 않아서 영원히 반복되는 상태

# ❌ 위험! 무한루프 (실행하지 마세요!) count = 1 while count <= 10: print(count) # count += 1을 빼먹음!

무한루프 방지법

1. 조건 변경 코드 확인

# ✅ 올바른 방법 count = 1 while count <= 10: print(count) count += 1 # 반드시 포함!

2. 안전장치 추가

# ✅ 안전장치가 있는 반복문 count = 1 safety_limit = 100 # 안전장치 while count <= 10 and count < safety_limit: print(count) count += 1

3. 명확한 종료 조건

# ✅ 명확한 종료 조건 user_input = "" while user_input != "종료": user_input = input("명령어 입력 ('종료'로 끝): ") if user_input == "안녕": print("안녕하세요!") elif user_input != "종료": print("알 수 없는 명령어입니다.") print("프로그램 종료")

🎲 while문 활용 예시

예시 1: 숫자 맞추기 게임

import random secret = random.randint(1, 10) guess = 0 print("1부터 10 사이의 숫자를 맞춰보세요!") while guess != secret: guess = int(input("숫자 입력: ")) if guess < secret: print("더 큰 수입니다!") elif guess > secret: print("더 작은 수입니다!") else: print("정답입니다!")

예시 2: 입력 검증

# 유효한 나이 입력받기 age = -1 while age < 0 or age > 150: age = int(input("나이를 입력하세요 (0-150): ")) if age < 0: print("나이는 0 이상이어야 합니다.") elif age > 150: print("나이는 150 이하여야 합니다.") print(f"입력하신 나이: {age}세")

예시 3: 점수 평균 계산

# 점수 입력받아 평균 계산 total = 0 count = 0 score = 0 print("점수를 입력하세요 (-1로 종료)") while score != -1: score = int(input("점수: ")) if score != -1: total += score count += 1 if count > 0: average = total / count print(f"평균 점수: {average:.1f}") else: print("입력된 점수가 없습니다.")

🚨 자주 발생하는 오류

오류 1: 무한루프

# ❌ 잘못된 예 i = 1 while i <= 5: print(i) # i += 1을 빼먹음! # ✅ 올바른 예 i = 1 while i <= 5: print(i) i += 1

오류 2: 조건식 실수

# ❌ 잘못된 예 count = 5 while count > 0 print(count) # SyntaxError: 콜론 누락! count -= 1 # ✅ 올바른 예 count = 5 while count > 0: # 콜론 필수! print(count) count -= 1

오류 3: 변수 초기화 실수

# ❌ 잘못된 예 while i <= 5: # NameError: i가 정의되지 않음! print(i) i += 1 # ✅ 올바른 예 i = 1 # 변수 초기화 필수! while i <= 5: print(i) i += 1

💡 퀴즈: while문 이해도 체크

Q1. 다음 코드는 몇 번 실행될까요?

count = 3 while count > 0: print("Hello") count -= 1
  1. 2번
  2. 3번
  3. 4번
  4. 무한루프

💡 정답 확인

정답: 2번 (3번)

count: 3 → 2 → 1 → 0(조건 거짓으로 종료) 따라서 “Hello”가 3번 출력됩니다.

Q2. 무한루프가 발생하는 경우는?

  1. 조건 변경 코드가 없을 때
  2. 조건이 항상 참일 때
  3. break문이 없을 때
  4. 1번과 2번 모두

💡 정답 확인

정답: 4번 (1번과 2번 모두)

조건 변경 코드가 없거나 조건이 항상 참이면 무한루프가 발생합니다.

Q3. break문의 역할은?

  1. 다음 반복으로 건너뛰기
  2. 반복문 완전히 종료
  3. 조건을 거짓으로 만들기
  4. 반복문 일시정지

💡 정답 확인

정답: 2번 (반복문 완전히 종료)

break는 반복문을 완전히 빠져나가는 역할을 합니다.

✅ while 반복문 마스터 체크리스트

✅ while 반복문 마스터 체크리스트

🚀 다음 단계

while 반복문을 익혔으니, 이제 더 편리한 반복문for문을 배워보겠습니다!

다음 토픽에서는:

  • for문: 정해진 횟수만큼 반복하기
  • range 함수: 숫자 범위 생성하기
  • 문자열 순회: 문자를 하나씩 처리하기

while문보다 더 간단하고 편리한 반복 방법을 알게 될 것입니다! 🎯

Last updated on