🐍 4w_for.py
📌 파이썬 반복,함수 핵심 정리 가이드 for · while · range ·function
// 파이썬 반목,함수 핵심 정리 가이드
AI소프트웨어과 · 4주차 강의노트

반복문. for / while

같은 작업을 여러 번 반복 실행하는 반복문 — for와 range(), while, break/continue, 중첩 반복문, enumerate()까지 정리한 4주차 강의 자료입니다.

01

반복문이란?

반복문(Loop)이란 같은 작업을 여러 번 반복해서 실행하는 문법입니다. 동일하거나 유사한 작업을 반복 수행할 때 사용하며, 반복 횟수가 정해진 경우(for)와 조건이 만족하는 동안 반복하는 경우(while)로 나뉩니다.

학생 30명의 점수 출력
1부터 100까지의 합 계산
구구단 출력
파일의 모든 줄 읽기
리스트의 모든 요소 출력
02

반복문의 종류

반복문설명사용 시기
for정해진 횟수 또는 데이터 개수만큼 반복리스트, 문자열, 범위(range) 순회
while조건이 참(True)인 동안 반복종료 시점을 조건으로 제어할 때
중첩 반복문반복문 안에 반복문 사용구구단, 별 출력, 2차원 데이터 처리
▶

for문과 range()

for_syntax.py
# for 변수 in 반복가능한객체:
#     실행문

# 반복 가능한 객체(Iterable)
# 문자열(str), 리스트(list), 튜플(tuple), 딕셔너리(dict), 집합(set), range()

range()는 일정한 범위의 숫자를 생성하는 함수입니다.

함수생성 값
range(5)0, 1, 2, 3, 4
range(1,6)1, 2, 3, 4, 5
range(2,11,2)2, 4, 6, 8, 10
range_demo.py
for i in range(5):
    print(i)

for i in range(1,6):
    print(i)
▶

자료형별 반복

문자열 & 리스트 반복
iter_str_list.py
word = "Python"

for ch in word:
    print(ch)

subjects = ["Python","AI","Web"]

for subject in subjects:
    print(subject)
튜플 반복
iter_tuple.py
colors = ("Red","Green","Blue")

for color in colors:
    print(color)
딕셔너리 반복
iter_dict.py
student = {
    "이름":"홍길동",
    "학년":1,
    "학과":"AI"
}

for key, value in student.items():
    print(key, value)
▶

합계 & 평균

sum_avg.py
#합계
total = 0

for i in range(1,11):
    total += i

print(total)

#평균
score = [90,85,100,95]

average = sum(score)/len(score)

print(average)

total = 0

for s in score:
    total += s

print(total/len(score))
▶

while문

조건
→
실행문
↻ 조건이 True인 동안 반복
while_basic.py
# while 조건:
#     실행문

i = 1

while i <= 5:
    print(i)
    i += 1
⚠️ while True:는 조건이 항상 참이므로 무한 반복됩니다 — Ctrl + C로 종료합니다.
infinite_loop.py
#무한반복 Ctrl+C 종료
while True:
    print("계속 실행")
▶

break & continue

break — 반복 즉시 종료
break_demo.py
for i in range(1,11):

    if i == 6:
        break

    print(i)
continue — 현재 반복만 건너뛰고 다음 반복 실행
continue_demo.py
for i in range(1,6):

    if i == 3:
        continue

    print(i)
▶

중첩 반복문

기본 중첩
nested_basic.py
for i in range(3):
    for j in range(2):
        print(i, j)
구구단
gugudan.py
for dan in range(2,10):

    print(f"[{dan}단]")

    for i in range(1,10):
        print(f"{dan} × {i} = {dan*i}")

    print()
삼각형 별 모양
triangle.py
for i in range(1,6):
    print("*"*i)
output
*
**
***
****
*****
▶

enumerate() & 종합예제

enumerate()는 인덱스와 값을 동시에 가져옵니다.

enumerate_demo.py
subjects = ["Python","AI","Web"]

for index, subject in enumerate(subjects):
    print(index, subject)
학생 성적 출력 — 종합예제
student_scores.py
students = {
    "홍길동":95,
    "김철수":88,
    "이영희":100
}

print("="*35)

for name, score in students.items():

    print(f"{name:10} {score}")

print("="*35)
10

for와 while 비교

항목forwhile
반복 횟수정해짐조건에 따라 달라짐
증가값자동직접 작성
사용 예리스트, 문자열, range메뉴 반복, 게임, 로그인
✎

실습 과제 1~6

과제 1

기초 — 1부터 10까지 출력

1부터 10까지 출력하세요.

과제 2

1~100 합계

1부터 100까지의 합을 구하세요.

과제 3

1~100 짝수만 출력

1부터 100까지의 짝수만 출력하세요.

과제 4

구구단 7단

구구단 7단을 출력하세요.

과제 5

0 입력 시 종료 — 누적 합계

사용자가 0을 입력할 때까지 숫자를 계속 입력받고, 입력한 숫자의 합을 출력하세요.

숫자 : 10 숫자 : 5 숫자 : 8 숫자 : 0 합계 : 23
과제 6

90점 이상 학생만 출력

학생 이름과 점수를 딕셔너리로 저장한 후, 90점 이상인 학생만 출력하세요.

students = { "홍길동":95, "김철수":88, "이영희":100, "박민수":75 }
과제 7

for, while ATM

다음 메뉴를 완성하고 종료시까지 while, for를 이용하여 반복하기


# 초기 잔액
balance = 100000

# 거래 내역을 저장할 리스트
transactions = []

while True:
    print("\n===== ATM =====")
    print("1. 잔액 확인")
    print("2. 입금")
    print("3. 출금")
    print("4. 종료")
    print("==============")

    choice = input("메뉴를 선택하세요: ")

    # 1. 잔액 확인
    if choice == "1":
        print(f"현재 잔액: {balance:,}원")

    # 2. 입금
    elif choice == "2":
        money = int(input("입금할 금액: "))
        balance += money
        transactions.append("입금")
        print(f"{money:,}원이 입금되었습니다.")
        print(f"현재 잔액: {balance:,}원")

    # 3. 출금
    elif choice == "3":
        money = int(input("출금할 금액: "))

        # 출금 가능 여부 판단
        if money <= balance:
            balance -= money
            transactions.append("출금")
            print(f"{money:,}원이 출금되었습니다.")
            print(f"현재 잔액: {balance:,}원")
        else:
            print("잔액이 부족합니다.")

    # 4. 종료
    elif choice == "4":
        print("ATM을 종료합니다.")
        break

    # 잘못된 메뉴
    else:
        print("잘못된 메뉴입니다.")


# 거래 횟수 출력
print("\n===== 거래 내역 =====")

count = 0

for transaction in transactions:
    count += 1
    print(f"{count}. {transaction}")

print(f"총 거래 횟수: {count}회")