<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>lullaby</title>
        <link>https://velog.io/</link>
        <description></description>
        <lastBuildDate>Tue, 06 Jan 2026 09:23:25 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>lullaby</title>
            <url>https://velog.velcdn.com/images/lullaby_/profile/fc604440-cab6-4b99-8ac6-3808e6b1fc15/image.png</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. lullaby. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/lullaby_" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[C++/Chapter4. 클래스와 객체]]></title>
            <link>https://velog.io/@lullaby_/CChapter4.-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EA%B0%9D%EC%B2%B4</link>
            <guid>https://velog.io/@lullaby_/CChapter4.-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EA%B0%9D%EC%B2%B4</guid>
            <pubDate>Tue, 06 Jan 2026 09:23:25 GMT</pubDate>
            <description><![CDATA[<h3 id="1-객체-지향-프로그래밍-oop">1. 객체 지향 프로그래밍 (OOP)</h3>
<h3 id="절차지향-vs-객체지향">절차지향 vs 객체지향</h3>
<p><strong>절차지향 프로그래밍</strong></p>
<ul>
<li>함수 중심의 프로그래밍</li>
<li>데이터와 기능이 분리</li>
<li>프로그램 = 함수들의 집합</li>
</ul>
<p><strong>객체지향 프로그래밍</strong></p>
<ul>
<li>클래스(설계도)를 사용</li>
<li>데이터와 기능이 하나로 묶임</li>
<li>객체 간 메시지 전달 방식</li>
<li>재사용성 향상 (정보은닉, 상속, 다형성, 캡슐화)</li>
</ul>
<h3 id="객체의-구성요소">객체의 구성요소</h3>
<ul>
<li><strong>상태(state)</strong>: 객체의 속성 → 멤버 변수</li>
<li><strong>동작(behavior)</strong>: 객체가 취할 수 있는 동작 → 멤버 함수</li>
</ul>
<hr>
<h3 id="2-클래스-작성-문법">2. 클래스 작성 문법</h3>
<h3 id="기본-구조">기본 구조</h3>
<pre><code class="language-cpp">class 클래스명 {
접근지정자:
    멤버변수;
    멤버함수();
};
</code></pre>
<h3 id="접근-지정자">접근 지정자</h3>
<table>
<thead>
<tr>
<th>지정자</th>
<th>접근 범위</th>
</tr>
</thead>
<tbody><tr>
<td><code>private</code></td>
<td>클래스 내부에서만 접근 가능</td>
</tr>
<tr>
<td><code>protected</code></td>
<td>클래스 내부 + <strong>상속된 클래스</strong>에서 접근 가능</td>
</tr>
<tr>
<td><code>public</code></td>
<td>어디서나 접근 가능</td>
</tr>
</tbody></table>
<hr>
<h3 id="3-핵심-문법-예제">3. 핵심 문법 예제</h3>
<h3 id="예제-1-기본-클래스-작성">예제 1: 기본 클래스 작성</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

class Circle {
public:
    int radius;
    string color;

    double calcArea() {
        return 3.14159 * radius * radius;
    }
};

int main() {
    Circle obj;
    obj.radius = 100;
    obj.color = &quot;blue&quot;;
    cout &lt;&lt; &quot;원의 면적은 &quot; &lt;&lt; obj.calcArea() &lt;&lt; &quot;입니다.&quot; &lt;&lt; endl;
    return 0;
}
</code></pre>
<h3 id="예제-2-여러-객체-생성">예제 2: 여러 객체 생성</h3>
<pre><code class="language-cpp">int main() {
    Circle pizza1, pizza2;

    pizza1.radius = 100;
    pizza1.color = &quot;yellow&quot;;
    cout &lt;&lt; &quot;피자1의 면적=&quot; &lt;&lt; pizza1.calcArea() &lt;&lt; &quot;\n&quot;;

    pizza2.radius = 200;
    pizza2.color = &quot;white&quot;;
    cout &lt;&lt; &quot;피자2의 면적=&quot; &lt;&lt; pizza2.calcArea() &lt;&lt; &quot;\n&quot;;

    return 0;
}
</code></pre>
<p><strong>중요</strong>: 각 객체의 멤버 변수 값은 독립적으로 관리됨!</p>
<h3 id="예제-3-함수-오버로딩">예제 3: 함수 오버로딩</h3>
<pre><code class="language-cpp">class PrintData {
public:
    void print(int i) { cout &lt;&lt; i &lt;&lt; endl; }
    void print(double f) { cout &lt;&lt; f &lt;&lt; endl; }
    void print(string s = &quot;No Data!&quot;) { cout &lt;&lt; s &lt;&lt; endl; }
};

int main() {
    PrintData obj;
    obj.print(1);           // int 버전 호출
    obj.print(3.14);        // double 버전 호출
    obj.print(&quot;C++14&quot;);     // string 버전 호출
    obj.print();            // 기본값 사용
    return 0;
}
</code></pre>
<hr>
<h3 id="4-클래스-선언과-정의-분리">4. 클래스 선언과 정의 분리</h3>
<h3 id="carh-헤더-파일">car.h (헤더 파일)</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

class Car {
    int speed;
    int gear;
    string color;
public:
    int getSpeed();
    void setSpeed(int s);
};
</code></pre>
<h3 id="carcpp-구현-파일">car.cpp (구현 파일)</h3>
<pre><code class="language-cpp">#include &quot;car.h&quot;

int Car::getSpeed() {
    return speed;
}

void Car::setSpeed(int s) {
    speed = s;
}
</code></pre>
<h3 id="maincpp-사용-파일">main.cpp (사용 파일)</h3>
<pre><code class="language-cpp">#include &quot;car.h&quot;

int main() {
    Car myCar;
    myCar.setSpeed(80);
    cout &lt;&lt; &quot;현재 속도는 &quot; &lt;&lt; myCar.getSpeed() &lt;&lt; endl;
    return 0;
}
</code></pre>
<h3 id="분리의-장점">분리의 장점</h3>
<p>✅ <strong>컴파일 시간 단축</strong>: 헤더가 변경되지 않으면 재컴파일 불필요</p>
<p>✅ <strong>정보 은닉</strong>: 구현 세부사항을 .cpp에 숨김</p>
<p>✅ <strong>코드 재사용</strong>: .h와 .cpp만 공유하면 됨</p>
<hr>
<h3 id="5-이름-공간-namespace">5. 이름 공간 (namespace)</h3>
<pre><code class="language-cpp">// 방법 1: 매번 std:: 사용
std::cout &lt;&lt; &quot;Hello&quot; &lt;&lt; std::endl;

// 방법 2: using namespace std 선언
using namespace std;
cout &lt;&lt; &quot;Hello&quot; &lt;&lt; endl;

// 방법 3: 특정 항목만 사용
using std::cout;
using std::endl;
</code></pre>
<p><strong>목적</strong>: 식별자의 충돌 방지, 논리적 그룹화</p>
<hr>
<h3 id="6-객체지향-4대-개념">6. 객체지향 4대 개념</h3>
<table>
<thead>
<tr>
<th>개념</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><strong>캡슐화</strong></td>
<td>데이터와 함수를 하나로 묶음</td>
</tr>
<tr>
<td><strong>정보은닉</strong></td>
<td>private으로 내부 구현 숨김</td>
</tr>
<tr>
<td><strong>상속</strong></td>
<td>기존 클래스의 특성을 물려받음</td>
</tr>
<tr>
<td><strong>다형성</strong></td>
<td>같은 함수명이 객체마다 다르게 동작</td>
</tr>
</tbody></table>
]]></description>
        </item>
        <item>
            <title><![CDATA[10시간 공부하고 ADsP 합격하는법]]></title>
            <link>https://velog.io/@lullaby_/10%EC%8B%9C%EA%B0%84-%EA%B3%B5%EB%B6%80%ED%95%98%EA%B3%A0-ADsP-%ED%95%A9%EA%B2%A9%ED%95%98%EB%8A%94%EB%B2%95</link>
            <guid>https://velog.io/@lullaby_/10%EC%8B%9C%EA%B0%84-%EA%B3%B5%EB%B6%80%ED%95%98%EA%B3%A0-ADsP-%ED%95%A9%EA%B2%A9%ED%95%98%EB%8A%94%EB%B2%95</guid>
            <pubDate>Mon, 24 Nov 2025 06:55:52 GMT</pubDate>
            <description><![CDATA[<p>안녕하세요?
제가 바로 그 _<strong>10시간의 용사</strong>_입니다
하하하
겸손하게 말하자면 *<em>이번은 개인적으로 공부 방식이 잘 맞아떨어진 케이스라고 생각되고, 누구에게나 동일하게 적용된다는 의미는 아닙니다. *</em>제 경험이 비슷한 계획을 가진 분들께 참고 자료가 되면 좋겠습니다.</p>
<p><img src="https://velog.velcdn.com/images/lullaby_/post/bf8982f4-8731-42af-92dd-6ae9c56045f3/image.png" alt="">
<img src="https://velog.velcdn.com/images/lullaby_/post/b3a560f3-75aa-4c93-a45e-8964c61e1a78/image.png" alt="">
마 턱걸이합격도 합격이다 아닙니까</p>
<p>하하하</p>
<p>공부시간 기록 (저는 공부시간을 기록하는 오랜 습관이 있습니다)
<img src="https://velog.velcdn.com/images/lullaby_/post/f55c0a51-8dd0-470f-913a-3c1ee4af0ad5/image.png" alt="">
<img src="https://velog.velcdn.com/images/lullaby_/post/d674ec4c-ceb7-4644-aae3-44117f260401/image.png" alt="">
공부시간 4:01 + 6:04
= 총 <em><strong>&quot;10시간 5분&quot;</strong></em>
(다른 것들은 무시해주십쇼)</p>
<p>사용교재:
<img src="https://velog.velcdn.com/images/lullaby_/post/ca9ec3cf-8c95-4baa-816c-9306e1e6ea7d/image.png" alt="">
학교에서 강의와 함께 제공해준 교재를 활용했습니다.
내돈내산이 아닌 책 후기를 올리게 되다니 감개무량하네요</p>
<h1 id="공부법위의-책-기준입니다"><strong>공부법(위의 책 기준입니다)</strong></h1>
<h3 id="1-강의를-듣는다12515배속">1. 강의를 듣는다(1.25~1.5배속)</h3>
<p>저는 아래 강의들을 활용했습니다. (댓글창에 일주일의 용사들이 많더군요)
1<del>2과목은  두 번 정도 들었고 3과목도 두 번 들었습니다. 이해 안 가는 부분은 반복해서 들으면 도움이 되더군요
<img src="https://velog.velcdn.com/images/lullaby_/post/a473dc4c-4b15-4c00-ae79-495331034047/image.png" alt="">
이 강의도 활용했습니다.(1</del>2과목 위주로 봤는데 딕션이 좋으시고 귀에 쏙쏙 들어오더군요)
<img src="https://velog.velcdn.com/images/lullaby_/post/6b9f6c62-3833-4548-8ba2-184237bc6f35/image.png" alt=""></p>
<h3 id="2-책의-개념부분을-푼다">2. 책의 개념부분을 푼다.</h3>
<p>앞에 개념 부분을 한두 번 읽고 바로 아래 있는 문제를 풉니다.
문제를 풀면서 개념을 익히는 방식이라고 할 수 있겠습니다.
틀린 문제는 해설을 보면서 왜 틀렸는지 확인하고 해설을 손으로 적어가면서 이해해줍니다. (눈으로만 읽으면 공부가 안됩니다. 쓰세요!)</p>
<h3 id="3-단원별-개념문제들을-풀어줍니다">3. 단원별 개념문제들을 풀어줍니다.</h3>
<p>보통 개념 - 해당 부분 기출문제(한두개) - 개념 - 단원 종합문제 이런 식으로 구성되어 있는데, 모른다고 다시 개념부분으로 회귀하는 등의 흐름을 끊는 행동을 하지 않고 쭉 풀어나갔습니다. 이렇게 3과목까지 풀어줍니다. 중간에 쉬는시간을 가질 경우 여기서 끊는 걸 권장드립니다. (개념-개념문제-단원별문제-쉬기-다음단원)</p>
<h3 id="4-헷갈리는-부분-확인-후-기출을-벅벅-푼다">4. 헷갈리는 부분 확인 후 기출을 벅벅 푼다</h3>
<p>저는 기출을 4세트정도 풀었는데 처음 푼 것 빼고 다 과락권이었습니다...(1, 2과목은 여유로운데 3과목에서 다 깎아먹어서)
개의치 않고 벅벅 풉니다.
채점 후 틀린 문제 오답을 열심히 합니다.
고등학교 시절 모의고사 오답했던 기억을 떠올려 오답을 해줍니다.</p>
<h3 id="5-시험을-봅니다">5. 시험을 봅니다.</h3>
<h3 id="6-잊습니다">6. 잊습니다.</h3>
<h3 id="7-합격-합격-합격">7. 합격! 합격! 합격!</h3>
<p>짧은 시간이었지만 효율적으로 준비한 덕분에 합격할 수 있었던 것 같습니다 ^^ 여러분도 충분히 하실 수 있어요 파이팅!</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[C++/Chapter03. 함수와 문자열]]></title>
            <link>https://velog.io/@lullaby_/CChapter03.-%ED%95%A8%EC%88%98%EC%99%80-%EB%AC%B8%EC%9E%90%EC%97%B4-atx654dx</link>
            <guid>https://velog.io/@lullaby_/CChapter03.-%ED%95%A8%EC%88%98%EC%99%80-%EB%AC%B8%EC%9E%90%EC%97%B4-atx654dx</guid>
            <pubDate>Wed, 01 Oct 2025 01:34:35 GMT</pubDate>
            <description><![CDATA[<h3 id="1️⃣-함수의-기본-개념">1️⃣ 함수의 기본 개념</h3>
<h3 id="핵심-개념">핵심 개념</h3>
<ul>
<li><strong>함수</strong>: 특정 작업을 수행하는 코드 블록</li>
<li><strong>함수 선언</strong>: 함수의 이름, 매개변수, 반환형을 미리 정의</li>
<li><strong>함수 호출</strong>: 정의된 함수를 실행하는 과정</li>
</ul>
<h3 id="핵심-문법">핵심 문법</h3>
<pre><code class="language-cpp">// 함수 선언 (함수 원형)
반환타입 함수명(매개변수);

// 함수 정의
반환타입 함수명(매개변수) {
    // 함수 본체
    return 값;
}

// 함수 호출
결과 = 함수명(인수);
</code></pre>
<h3 id="예제-코드">예제 코드</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

// 함수 원형 선언
int max(int x, int y);

int main() {
    int result = max(10, 20);  // 함수 호출
    cout &lt;&lt; &quot;최댓값: &quot; &lt;&lt; result &lt;&lt; endl;
    return 0;
}

// 함수 정의
int max(int x, int y) {
    if (x &gt; y)
        return x;
    else
        return y;
}
</code></pre>
<hr>
<h3 id="2️⃣-인수-전달-방법">2️⃣ 인수 전달 방법</h3>
<h3 id="핵심-개념-1">핵심 개념</h3>
<ol>
<li><strong>값으로 호출 (Call-by-Value)</strong><ul>
<li>인수의 값이 매개변수로 복사됨</li>
<li>원본 값은 변경되지 않음</li>
</ul>
</li>
<li><strong>참조로 호출 (Call-by-Reference)</strong><ul>
<li>인수의 주소가 전달됨</li>
<li>원본 값이 직접 변경됨</li>
</ul>
</li>
</ol>
<h3 id="핵심-문법-1">핵심 문법</h3>
<pre><code class="language-cpp">// 값으로 전달
void func1(int x) {
    x = 100;  // 원본 변경 안됨
}

// 참조로 전달
void func2(int&amp; x) {
    x = 100;  // 원본 변경됨
}
</code></pre>
<h3 id="예제-코드---swap-함수">예제 코드 - swap 함수</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

void swap(int&amp; x, int&amp; y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 100, b = 200;
    cout &lt;&lt; &quot;교환 전: a=&quot; &lt;&lt; a &lt;&lt; &quot;, b=&quot; &lt;&lt; b &lt;&lt; endl;
    swap(a, b);
    cout &lt;&lt; &quot;교환 후: a=&quot; &lt;&lt; a &lt;&lt; &quot;, b=&quot; &lt;&lt; b &lt;&lt; endl;
    return 0;
}
</code></pre>
<hr>
<h3 id="3️⃣-중복-함수-function-overloading">3️⃣ 중복 함수 (Function Overloading)</h3>
<h3 id="핵심-개념-2">핵심 개념</h3>
<ul>
<li>동일한 이름의 함수를 매개변수 타입이나 개수를 다르게 하여 여러 개 정의</li>
<li>컴파일러가 호출 시 적절한 함수를 자동 선택</li>
</ul>
<h3 id="예제-코드-1">예제 코드</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int square(int i) {
    cout &lt;&lt; &quot;정수 제곱 함수 호출&quot; &lt;&lt; endl;
    return i * i;
}

double square(double i) {
    cout &lt;&lt; &quot;실수 제곱 함수 호출&quot; &lt;&lt; endl;
    return i * i;
}

void print(int i) { cout &lt;&lt; &quot;정수: &quot; &lt;&lt; i &lt;&lt; endl; }
void print(double f) { cout &lt;&lt; &quot;실수: &quot; &lt;&lt; f &lt;&lt; endl; }
void print(char c) { cout &lt;&lt; &quot;문자: &quot; &lt;&lt; c &lt;&lt; endl; }
</code></pre>
<hr>
<h3 id="4️⃣-디폴트-매개변수">4️⃣ 디폴트 매개변수</h3>
<h3 id="핵심-개념-3">핵심 개념</h3>
<ul>
<li>함수 호출 시 인수가 전달되지 않으면 기본값을 사용</li>
<li>마지막 매개변수부터 디폴트 값을 설정해야 함</li>
</ul>
<h3 id="핵심-문법-2">핵심 문법</h3>
<pre><code class="language-cpp">반환타입 함수명(타입 변수1, 타입 변수2 = 기본값, 타입 변수3 = 기본값);
</code></pre>
<h3 id="예제-코드-2">예제 코드</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

void display(char c = &#39;*&#39;, int n = 10) {
    for (int i = 0; i &lt; n; i++)
        cout &lt;&lt; c;
    cout &lt;&lt; endl;
}

int sum(int x, int y, int z = 0, int w = 0) {
    return x + y + z + w;
}

int main() {
    display();           // 모든 기본값 사용
    display(&#39;#&#39;);        // c=&#39;#&#39;, n=10(기본값)
    display(&#39;#&#39;, 5);     // 모든 값 지정

    cout &lt;&lt; sum(10, 20) &lt;&lt; endl;        // 30
    cout &lt;&lt; sum(10, 20, 30) &lt;&lt; endl;    // 60
    cout &lt;&lt; sum(10, 20, 30, 40) &lt;&lt; endl; // 100
    return 0;
}
</code></pre>
<hr>
<h3 id="5️⃣-인라인-함수">5️⃣ 인라인 함수</h3>
<h3 id="핵심-개념-4">핵심 개념</h3>
<ul>
<li><code>inline</code> 키워드를 사용하여 함수 호출 오버헤드를 줄임</li>
<li>컴파일러가 함수 코드를 호출 위치에 직접 삽입</li>
<li>간단하고 자주 호출되는 함수에 적합</li>
</ul>
<h3 id="예제-코드-3">예제 코드</h3>
<pre><code class="language-cpp">inline double square(double i) {
    return i * i;
}

inline int max(int a, int b) {
    return (a &gt; b) ? a : b;
}
</code></pre>
<hr>
<h3 id="6️⃣-string-클래스">6️⃣ string 클래스</h3>
<h3 id="핵심-개념-5">핵심 개념</h3>
<ul>
<li>C++에서 문자열을 다루기 위한 클래스</li>
<li><code>&lt;string&gt;</code> 헤더 파일 포함 필요</li>
<li>동적 크기 조정, 다양한 멤버 함수 제공</li>
</ul>
<h3 id="핵심-문법-3">핵심 문법</h3>
<pre><code class="language-cpp">#include &lt;string&gt;
using namespace std;

string s;                    // 빈 문자열 생성
string s = &quot;Hello&quot;;          // 초기화
string s{&quot;Hello&quot;};           // 보편적 초기화
</code></pre>
<h3 id="주요-연산자와-함수">주요 연산자와 함수</h3>
<pre><code class="language-cpp">// 문자열 연산
string s1 = &quot;Hello&quot;;
string s2 = &quot;World&quot;;
string s3 = s1 + &quot; &quot; + s2;   // 문자열 결합
s3 += &quot;!&quot;;                   // 문자열 추가

// 문자열 비교
if (s1 == s2) { }            // 동등 비교
if (s1 &gt; s2) { }             // 사전식 비교

// 주요 멤버 함수
s.length()                   // 문자열 길이
s.find(&quot;text&quot;)              // 부분 문자열 찾기
s[i]                        // i번째 문자 접근
getline(cin, s)             // 공백 포함 문자열 입력
</code></pre>
<h3 id="예제-코드-4">예제 코드</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

int main() {
    string name, address;

    cout &lt;&lt; &quot;이름을 입력하세요: &quot;;
    cin &gt;&gt; name;
    cin.ignore();  // 버퍼 정리

    cout &lt;&lt; &quot;주소를 입력하세요: &quot;;
    getline(cin, address);

    cout &lt;&lt; address &lt;&lt; &quot;의 &quot; &lt;&lt; name &lt;&lt; &quot;씨 안녕하세요!&quot; &lt;&lt; endl;

    // 문자열 검색
    string text = &quot;When in Rome, do as the Romans.&quot;;
    int pos = text.find(&quot;Rome&quot;);
    cout &lt;&lt; &quot;Rome의 위치: &quot; &lt;&lt; pos &lt;&lt; endl;

    return 0;
}
</code></pre>
<hr>
<h2 id="🔥-예상-문제-및-실전-대비">🔥 예상 문제 및 실전 대비</h2>
<h3 id="📝-예상-문제-1-함수-기본-★★☆">📝 예상 문제 1: 함수 기본 (★★☆)</h3>
<pre><code class="language-cpp">// 다음 코드의 출력 결과를 예측하시오
#include &lt;iostream&gt;
using namespace std;

int calculate(int a, int b = 5) {
    return a * b;
}

int main() {
    cout &lt;&lt; calculate(3) &lt;&lt; endl;
    cout &lt;&lt; calculate(3, 2) &lt;&lt; endl;
    return 0;
}
</code></pre>
<p><strong>정답</strong>: 15, 6</p>
<p><strong>해설</strong>: 첫 번째 호출에서는 b의 기본값 5가 사용되어 3×5=15, 두 번째 호출에서는 b=2가 전달되어 3×2=6</p>
<hr>
<h3 id="📝-예상-문제-2-참조-전달-★★★">📝 예상 문제 2: 참조 전달 (★★★)</h3>
<pre><code class="language-cpp">// 다음 코드를 완성하여 두 변수의 값을 교환하는 함수를 작성하시오
#include &lt;iostream&gt;
using namespace std;

void swap(_______ a, _______ b) {
    _______________________
    _______________________
    _______________________
}

int main() {
    int x = 10, y = 20;
    cout &lt;&lt; &quot;교환 전: x=&quot; &lt;&lt; x &lt;&lt; &quot;, y=&quot; &lt;&lt; y &lt;&lt; endl;
    swap(x, y);
    cout &lt;&lt; &quot;교환 후: x=&quot; &lt;&lt; x &lt;&lt; &quot;, y=&quot; &lt;&lt; y &lt;&lt; endl;
    return 0;
}
</code></pre>
<p><strong>정답</strong>:</p>
<pre><code class="language-cpp">void swap(int&amp; a, int&amp; b) {
    int temp = a;
    a = b;
    b = temp;
}
</code></pre>
<hr>
<h3 id="📝-예상-문제-3-중복-함수-★★★">📝 예상 문제 3: 중복 함수 (★★★)</h3>
<pre><code class="language-cpp">// 다음과 같이 동작하는 중복 함수 print를 작성하시오
// print(100) → &quot;정수: 100&quot;
// print(3.14) → &quot;실수: 3.14&quot;
// print(&#39;A&#39;) → &quot;문자: A&quot;

#include &lt;iostream&gt;
using namespace std;

// 여기에 중복 함수들을 작성하시오
_________________________________
_________________________________
_________________________________

int main() {
    print(100);
    print(3.14);
    print(&#39;A&#39;);
    return 0;
}
</code></pre>
<p><strong>정답</strong>:</p>
<pre><code class="language-cpp">void print(int i) {
    cout &lt;&lt; &quot;정수: &quot; &lt;&lt; i &lt;&lt; endl;
}

void print(double f) {
    cout &lt;&lt; &quot;실수: &quot; &lt;&lt; f &lt;&lt; endl;
}

void print(char c) {
    cout &lt;&lt; &quot;문자: &quot; &lt;&lt; c &lt;&lt; endl;
}
</code></pre>
<hr>
<h3 id="📝-예상-문제-4-string-클래스-활용-★★★">📝 예상 문제 4: string 클래스 활용 (★★★)</h3>
<pre><code class="language-cpp">// 사용자로부터 문자열을 입력받아 특정 문자의 개수를 세는 프로그램을 완성하시오
#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

int main() {
    string text;
    char target;
    int count = 0;

    cout &lt;&lt; &quot;문자열을 입력하세요: &quot;;
    getline(cin, text);
    cout &lt;&lt; &quot;찾을 문자를 입력하세요: &quot;;
    cin &gt;&gt; target;

    // 여기에 문자 개수를 세는 코드를 작성하시오
    _________________________________
    _________________________________
    _________________________________

    cout &lt;&lt; &quot;&#39;&quot; &lt;&lt; target &lt;&lt; &quot;&#39; 문자의 개수: &quot; &lt;&lt; count &lt;&lt; endl;
    return 0;
}
</code></pre>
<p><strong>정답</strong>:</p>
<pre><code class="language-cpp">for (int i = 0; i &lt; text.length(); i++) {
    if (text[i] == target) {
        count++;
    }
}
</code></pre>
<p><strong>또는</strong>:</p>
<pre><code class="language-cpp">for (char c : text) {
    if (c == target) {
        count++;
    }
}
</code></pre>
<hr>
<h3 id="📝-예상-문제-5-해밍-거리-★★★★">📝 예상 문제 5: 해밍 거리 (★★★★)</h3>
<pre><code class="language-cpp">// 두 DNA 문자열의 해밍 거리를 구하는 프로그램을 작성하시오
// 해밍 거리: 같은 위치에서 다른 문자의 개수

#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

int hammingDistance(string s1, string s2) {
    // 여기에 해밍 거리를 계산하는 코드를 작성하시오
    _________________________________
    _________________________________
    _________________________________
}

int main() {
    string dna1, dna2;
    cout &lt;&lt; &quot;DNA1: &quot;;
    cin &gt;&gt; dna1;
    cout &lt;&lt; &quot;DNA2: &quot;;
    cin &gt;&gt; dna2;

    if (dna1.length() != dna2.length()) {
        cout &lt;&lt; &quot;오류: 길이가 다릅니다.&quot; &lt;&lt; endl;
    } else {
        int distance = hammingDistance(dna1, dna2);
        cout &lt;&lt; &quot;해밍 거리: &quot; &lt;&lt; distance &lt;&lt; endl;
    }
    return 0;
}
</code></pre>
<p><strong>정답</strong>:</p>
<pre><code class="language-cpp">int hammingDistance(string s1, string s2) {
    int count = 0;
    for (int i = 0; i &lt; s1.length(); i++) {
        if (s1[i] != s2[i]) {
            count++;
        }
    }
    return count;
}
</code></pre>
<hr>
<h2 id="🎯-실전-대비-핵심-포인트">🎯 실전 대비 핵심 포인트</h2>
<h3 id="✅-함수-관련-체크포인트">✅ 함수 관련 체크포인트</h3>
<ol>
<li><strong>함수 원형 선언</strong>을 main() 함수 앞에 작성했는가?</li>
<li><strong>참조 전달</strong>이 필요한 경우 <code>&amp;</code> 연산자를 사용했는가?</li>
<li><strong>중복 함수</strong>에서 매개변수 타입이 다른가?</li>
<li><strong>디폴트 매개변수</strong>를 오른쪽부터 설정했는가?</li>
</ol>
<h3 id="✅-string-관련-체크포인트">✅ string 관련 체크포인트</h3>
<ol>
<li><code>#include &lt;string&gt;</code> 헤더를 포함했는가?</li>
<li><strong>공백 포함 입력</strong>에는 <code>getline()</code>을 사용했는가?</li>
<li><code>cin</code> 후 <code>getline()</code> 사용 시 <code>cin.ignore()</code>를 호출했는가?</li>
<li><strong>문자열 길이</strong>는 <code>length()</code> 또는 <code>size()</code> 함수로 구했는가?</li>
</ol>
<h3 id="⚠️-주의사항">⚠️ 주의사항</h3>
<ul>
<li>함수에서 지역변수는 함수 종료 시 소멸됨</li>
<li>참조 전달 시 원본이 변경되므로 주의 필요</li>
<li>string 객체는 동적으로 크기가 변함</li>
<li>배열 인덱스는 0부터 시작함</li>
</ul>
<hr>
<h2 id="📖-추가-연습-문제">📖 추가 연습 문제</h2>
<h3 id="연습문제-1">연습문제 1</h3>
<p>팩토리얼을 계산하는 함수를 작성하고, 중복 함수로 int와 long long 타입을 모두 처리하도록 하시오.</p>
<h3 id="연습문제-2">연습문제 2</h3>
<p>문자열에서 모든 공백을 제거하는 함수를 작성하시오.</p>
<h3 id="연습문제-3">연습문제 3</h3>
<p>두 문자열이 애너그램(같은 글자로 구성되었지만 순서가 다른 단어)인지 판별하는 함수를 작성하시오.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[C++/Chapter02. 제어구조와 배열]]></title>
            <link>https://velog.io/@lullaby_/CChapter02.-%EC%A0%9C%EC%96%B4%EA%B5%AC%EC%A1%B0%EC%99%80-%EB%B0%B0%EC%97%B4</link>
            <guid>https://velog.io/@lullaby_/CChapter02.-%EC%A0%9C%EC%96%B4%EA%B5%AC%EC%A1%B0%EC%99%80-%EB%B0%B0%EC%97%B4</guid>
            <pubDate>Wed, 01 Oct 2025 01:33:30 GMT</pubDate>
            <description><![CDATA[<p>제어에서 가장 중요한 건 <strong>조건</strong></p>
<p>시퀀스가 있기 때문에 루프가 가능함</p>
<p>stream manipulator <strong>boolalpha</strong></p>
<hr>
<h2 id="1-관계연산자와-논리연산자">1. 관계연산자와 논리연산자</h2>
<h3 id="핵심-개념">핵심 개념</h3>
<ul>
<li><strong>관계연산자</strong>: <code>==</code>, <code>!=</code>, <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code></li>
<li><strong>논리연산자</strong>: <code>&amp;&amp;</code>(AND), <code>||</code>(OR), <code>!</code>(NOT)</li>
<li><strong>bool 타입</strong>: true/false 값을 저장</li>
</ul>
<h3 id="중요-문법">중요 문법</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    bool b = (1 == 2);  // false
    cout &lt;&lt; boolalpha;  // bool 값을 true/false로 출력
    cout &lt;&lt; b &lt;&lt; endl;  // false 출력
    return 0;
}
</code></pre>
<hr>
<h2 id="2-if-else-문">2. if-else 문</h2>
<h3 id="핵심-구조">핵심 구조</h3>
<pre><code class="language-cpp">if (조건) {
    // 조건이 참일 때 실행
} else {
    // 조건이 거짓일 때 실행
}
</code></pre>
<h3 id="실전-예제">실전 예제</h3>
<pre><code class="language-cpp">// 두 수 중 큰 값 찾기
int x, y;
cin &gt;&gt; x &gt;&gt; y;
if (x &gt; y)
    cout &lt;&lt; &quot;x가 y보다 큽니다.&quot; &lt;&lt; endl;
else
    cout &lt;&lt; &quot;y가 x보다 큽니다.&quot; &lt;&lt; endl;
</code></pre>
<hr>
<h2 id="3-중첩-if-else-문">3. 중첩 if-else 문</h2>
<h3 id="핵심-구조-1">핵심 구조</h3>
<pre><code class="language-cpp">if (조건1) {
    // 조건1이 참
} else if (조건2) {
    // 조건1은 거짓, 조건2는 참
} else {
    // 모든 조건이 거짓
}
</code></pre>
<h3 id="실전-예제---나이별-구분">실전 예제 - 나이별 구분</h3>
<pre><code class="language-cpp">int age;
cin &gt;&gt; age;
if (age &lt;= 12)
    cout &lt;&lt; &quot;어린이입니다.&quot; &lt;&lt; endl;
else if (age &lt;= 19)
    cout &lt;&lt; &quot;청소년입니다.&quot; &lt;&lt; endl;
else
    cout &lt;&lt; &quot;성인입니다.&quot; &lt;&lt; endl;
</code></pre>
<hr>
<h2 id="4-switch-문">4. switch 문</h2>
<h3 id="핵심-구조-2">핵심 구조</h3>
<pre><code class="language-cpp">switch (변수) {
    case 값1:
        문장1;
        break;
    case 값2:
        문장2;
        break;
    default:
        기본문장;
        break;
}
</code></pre>
<h3 id="주의사항">주의사항</h3>
<ul>
<li><strong>break 문 필수</strong>: break가 없으면 다음 case로 넘어감</li>
<li><strong>정수형/문자형만 가능</strong>: 실수형은 사용 불가</li>
</ul>
<hr>
<h2 id="5-반복문">5. 반복문</h2>
<h3 id="51-while-문">5.1 while 문</h3>
<pre><code class="language-cpp">int n = 10;
while (n &gt; 0) {
    cout &lt;&lt; n &lt;&lt; &quot; &quot;;
    n--;
}
</code></pre>
<h3 id="52-do-while-문">5.2 do-while 문</h3>
<pre><code class="language-cpp">string str;
do {
    cout &lt;&lt; &quot;문자열을 입력하시오: &quot;;
    getline(cin, str);
    cout &lt;&lt; &quot;사용자의 입력: &quot; &lt;&lt; str &lt;&lt; endl;
} while (str != &quot;종료&quot;);
</code></pre>
<h3 id="53-for-문">5.3 for 문</h3>
<pre><code class="language-cpp">// 1부터 10까지 합계
int sum = 0;
for (int i = 1; i &lt;= 10; i++) {
    sum += i;
}
cout &lt;&lt; &quot;합계: &quot; &lt;&lt; sum &lt;&lt; endl;
</code></pre>
<h3 id="차이점-정리">차이점 정리</h3>
<ul>
<li><strong>while</strong>: 조건을 먼저 확인 (0번 실행 가능)</li>
<li><strong>do-while</strong>: 최소 1번은 실행</li>
<li><strong>for</strong>: 초기값, 조건, 증감식이 명확할 때 사용</li>
</ul>
<hr>
<h2 id="6-break와-continue">6. break와 continue</h2>
<h3 id="break-문">break 문</h3>
<pre><code class="language-cpp">for (int i = 1; i &lt; 10; i++) {
    cout &lt;&lt; i &lt;&lt; &quot; &quot;;
    if (i == 4)
        break;  // 루프 종료
}
// 출력: 1 2 3 4
</code></pre>
<h3 id="continue-문">continue 문</h3>
<pre><code class="language-cpp">for (int i = 1; i &lt;= 5; i++) {
    if (i == 3)
        continue;  // 3일 때 건너뛰기
    cout &lt;&lt; i &lt;&lt; &quot; &quot;;
}
// 출력: 1 2 4 5
</code></pre>
<hr>
<h2 id="7-배열">7. 배열</h2>
<h3 id="71-배열-선언과-초기화">7.1 배열 선언과 초기화</h3>
<pre><code class="language-cpp">// 선언
int scores[10];

// 초기화
int sales[5] = {100, 200, 300, 400, 500};
int sales[] = {100, 200, 300};  // 크기 자동 결정

// 보편적 초기화 (C++11)
int scores[]{10, 20, 30};
</code></pre>
<h3 id="72-범위-기반-for-루프">7.2 범위 기반 for 루프</h3>
<pre><code class="language-cpp">int list[] = {1, 2, 3, 4, 5};

// 읽기만
for (int i : list) {
    cout &lt;&lt; i &lt;&lt; &quot; &quot;;
}

// 수정 가능
for (int&amp; i : list) {
    i = i * 2;  // 값 변경
}

// 자동 타입 추론
for (auto&amp; i : list) {
    cout &lt;&lt; i &lt;&lt; &quot; &quot;;
}
</code></pre>
<hr>
<h2 id="8-2차원-배열">8. 2차원 배열</h2>
<h3 id="81-선언과-초기화">8.1 선언과 초기화</h3>
<pre><code class="language-cpp">// 선언
int s[3][5];

// 초기화
int table[3][5] = {
    {1, 2, 3, 4, 5},
    {2, 4, 6, 8, 10},
    {3, 6, 9, 12, 15}
};
</code></pre>
<h3 id="82-접근-방법">8.2 접근 방법</h3>
<pre><code class="language-cpp">// 이중 반복문으로 접근
for (int r = 0; r &lt; 3; r++) {
    for (int c = 0; c &lt; 5; c++) {
        cout &lt;&lt; table[r][c] &lt;&lt; &quot; &quot;;
    }
    cout &lt;&lt; endl;
}
</code></pre>
<hr>
<h2 id="9-예상-문제-및-해답">9. 예상 문제 및 해답</h2>
<h3 id="🔥-예상문제-1-조건문-난이도-★★☆">🔥 예상문제 1: 조건문 (난이도: ★★☆)</h3>
<p><strong>문제</strong>: 사용자로부터 점수를 입력받아 학점을 출력하는 프로그램을 작성하시오.</p>
<ul>
<li>90점 이상: A</li>
<li>80점 이상: B</li>
<li>70점 이상: C</li>
<li>60점 이상: D</li>
<li>60점 미만: F</li>
</ul>
<p><strong>해답</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    int score;
    cout &lt;&lt; &quot;점수를 입력하세요: &quot;;
    cin &gt;&gt; score;

    if (score &gt;= 90)
        cout &lt;&lt; &quot;학점: A&quot; &lt;&lt; endl;
    else if (score &gt;= 80)
        cout &lt;&lt; &quot;학점: B&quot; &lt;&lt; endl;
    else if (score &gt;= 70)
        cout &lt;&lt; &quot;학점: C&quot; &lt;&lt; endl;
    else if (score &gt;= 60)
        cout &lt;&lt; &quot;학점: D&quot; &lt;&lt; endl;
    else
        cout &lt;&lt; &quot;학점: F&quot; &lt;&lt; endl;

    return 0;
}
</code></pre>
<h3 id="🔥-예상문제-2-반복문-난이도-★★☆">🔥 예상문제 2: 반복문 (난이도: ★★☆)</h3>
<p><strong>문제</strong>: 1부터 n까지의 수 중에서 홀수만의 합을 구하는 프로그램을 작성하시오.</p>
<p><strong>해답</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    int n, sum = 0;
    cout &lt;&lt; &quot;n을 입력하세요: &quot;;
    cin &gt;&gt; n;

    for (int i = 1; i &lt;= n; i++) {
        if (i % 2 == 1) {  // 홀수일 때
            sum += i;
        }
    }

    cout &lt;&lt; &quot;1부터 &quot; &lt;&lt; n &lt;&lt; &quot;까지 홀수의 합: &quot; &lt;&lt; sum &lt;&lt; endl;
    return 0;
}
</code></pre>
<h3 id="🔥-예상문제-3-배열-난이도-★★★">🔥 예상문제 3: 배열 (난이도: ★★★)</h3>
<p><strong>문제</strong>: 10개의 정수를 배열에 저장하고, 배열에서 최댓값과 최솟값을 찾아 출력하는 프로그램을 작성하시오.</p>
<p><strong>해답</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    int numbers[10];

    // 배열에 값 입력
    cout &lt;&lt; &quot;10개의 정수를 입력하세요: &quot;;
    for (int i = 0; i &lt; 10; i++) {
        cin &gt;&gt; numbers[i];
    }

    // 최댓값과 최솟값 찾기
    int max = numbers[0];
    int min = numbers[0];

    for (int i = 1; i &lt; 10; i++) {
        if (numbers[i] &gt; max)
            max = numbers[i];
        if (numbers[i] &lt; min)
            min = numbers[i];
    }

    cout &lt;&lt; &quot;최댓값: &quot; &lt;&lt; max &lt;&lt; endl;
    cout &lt;&lt; &quot;최솟값: &quot; &lt;&lt; min &lt;&lt; endl;

    return 0;
}
</code></pre>
<h3 id="🔥-예상문제-4-2차원-배열-난이도-★★★">🔥 예상문제 4: 2차원 배열 (난이도: ★★★)</h3>
<p><strong>문제</strong>: 3×3 행렬의 각 행의 합을 구하는 프로그램을 작성하시오.</p>
<p><strong>해답</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    int matrix[3][3];

    // 행렬 입력
    cout &lt;&lt; &quot;3x3 행렬을 입력하세요:&quot; &lt;&lt; endl;
    for (int i = 0; i &lt; 3; i++) {
        for (int j = 0; j &lt; 3; j++) {
            cin &gt;&gt; matrix[i][j];
        }
    }

    // 각 행의 합 계산
    for (int i = 0; i &lt; 3; i++) {
        int rowSum = 0;
        for (int j = 0; j &lt; 3; j++) {
            rowSum += matrix[i][j];
        }
        cout &lt;&lt; &quot;행 &quot; &lt;&lt; (i+1) &lt;&lt; &quot;의 합: &quot; &lt;&lt; rowSum &lt;&lt; endl;
    }

    return 0;
}
</code></pre>
<h3 id="🔥-예상문제-5-종합-문제-난이도-★★★">🔥 예상문제 5: 종합 문제 (난이도: ★★★)</h3>
<p><strong>문제</strong>: 학생 5명의 3과목 점수를 2차원 배열에 저장하고, 각 학생의 평균과 전체 평균을 구하는 프로그램을 작성하시오.</p>
<p><strong>해답</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    int scores[5][3];  // 5명의 학생, 3과목

    // 점수 입력
    for (int i = 0; i &lt; 5; i++) {
        cout &lt;&lt; &quot;학생 &quot; &lt;&lt; (i+1) &lt;&lt; &quot;의 3과목 점수를 입력하세요: &quot;;
        for (int j = 0; j &lt; 3; j++) {
            cin &gt;&gt; scores[i][j];
        }
    }

    int totalSum = 0;

    // 각 학생의 평균 계산
    for (int i = 0; i &lt; 5; i++) {
        int studentSum = 0;
        for (int j = 0; j &lt; 3; j++) {
            studentSum += scores[i][j];
        }
        totalSum += studentSum;
        double average = studentSum / 3.0;
        cout &lt;&lt; &quot;학생 &quot; &lt;&lt; (i+1) &lt;&lt; &quot;의 평균: &quot; &lt;&lt; average &lt;&lt; endl;
    }

    // 전체 평균
    double totalAverage = totalSum / 15.0;  // 5명 × 3과목 = 15
    cout &lt;&lt; &quot;전체 평균: &quot; &lt;&lt; totalAverage &lt;&lt; endl;

    return 0;
}
</code></pre>
<hr>
<h2 id="📝-시험-대비-체크리스트">📝 시험 대비 체크리스트</h2>
<h3 id="꼭-암기해야-할-것들">꼭 암기해야 할 것들</h3>
<ul>
<li><input disabled="" type="checkbox"> if-else 문의 기본 구조</li>
<li><input disabled="" type="checkbox"> for 문의 3가지 구성요소 (초기화; 조건; 증감)</li>
<li><input disabled="" type="checkbox"> 배열 선언과 초기화 문법</li>
<li><input disabled="" type="checkbox"> 2차원 배열 접근 방법</li>
<li><input disabled="" type="checkbox"> break와 continue의 차이점</li>
<li><input disabled="" type="checkbox"> 범위 기반 for 루프 문법</li>
</ul>
<h3 id="자주-나오는-실수들">자주 나오는 실수들</h3>
<ol>
<li><strong>세미콜론 빠뜨리기</strong>: if문 뒤에 세미콜론 사용 금지</li>
<li><strong>배열 인덱스</strong>: 0부터 시작, 크기-1까지</li>
<li><strong>break 누락</strong>: switch문에서 break 빠뜨리기</li>
<li><strong>초기화 안함</strong>: 변수 사용 전 반드시 초기화</li>
<li><strong>참조자 사용</strong>: 배열 요소 수정할 때 <code>int&amp;</code> 사용
int&amp;은 참조를 의미, 이미 존재하는 변수나 객체에 대한 별명 역할</li>
</ol>
<h3 id="시험장에서-주의사항">시험장에서 주의사항</h3>
<ul>
<li>문제를 정확히 읽고 요구사항 파악</li>
<li>변수명과 출력 형식 정확히 따르기</li>
<li>컴파일 에러가 나지 않도록 문법 확인</li>
<li>논리 오류가 없는지 간단한 값으로 검증</li>
</ul>
<hr>
<h2 id="🎯-최종-점검-문제">🎯 최종 점검 문제</h2>
<p><strong>문제</strong>: 다음 코드의 출력 결과를 예측하시오.</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};

    for (int i = 0; i &lt; 5; i++) {
        if (i % 2 == 0)
            continue;
        cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;
    }

    cout &lt;&lt; endl;

    for (auto&amp; x : arr) {
        x *= 2;
    }

    for (int x : arr) {
        cout &lt;&lt; x &lt;&lt; &quot; &quot;;
    }

    return 0;
}
</code></pre>
<p><strong>정답</strong>:</p>
<pre><code>2 4
2 4 6 8 10
</code></pre><p><strong>해설</strong>:</p>
<ul>
<li>첫 번째 루프: i가 짝수일 때 continue하므로 홀수 인덱스(1, 3)의 값인 2, 4 출력</li>
<li>두 번째 루프: 모든 배열 요소를 2배로 변경</li>
<li>세 번째 루프: 변경된 배열 전체 출력</li>
</ul>
<hr>
]]></description>
        </item>
        <item>
            <title><![CDATA[C++/Chapter01. 기초사항 정리]]></title>
            <link>https://velog.io/@lullaby_/CChapter01.-%EA%B8%B0%EC%B4%88%EC%82%AC%ED%95%AD-%EC%A0%95%EB%A6%AC</link>
            <guid>https://velog.io/@lullaby_/CChapter01.-%EA%B8%B0%EC%B4%88%EC%82%AC%ED%95%AD-%EC%A0%95%EB%A6%AC</guid>
            <pubDate>Wed, 01 Oct 2025 01:32:14 GMT</pubDate>
            <description><![CDATA[<h2 id="📚-1-c-언어의-역사와-특징">📚 1. C++ 언어의 역사와 특징</h2>
<h3 id="핵심-개념">핵심 개념</h3>
<ul>
<li><strong>개발자</strong>: Bjarne Stroustrup (비야네 스트로스트룹, 덴마크)</li>
<li><strong>개발 시기</strong>: 1980년대 초, AT&amp;T 벨연구소</li>
<li><strong>발전 과정</strong>: C with Classes → C++</li>
<li><strong>표준화</strong>: ANSI와 ISO에 의해 공동 개발 (1997년 공식 표준)</li>
</ul>
<h3 id="c의-주요-특징">C++의 주요 특징</h3>
<ol>
<li><strong>클래스(class)</strong>: 객체의 속성과 동작 정의</li>
<li><strong>상속(inheritance)</strong>: 코드 재사용</li>
<li><strong>연산자 중복(operator overloading)</strong>: 동일 연산자로 새로운 연산 정의</li>
<li><strong>함수 중복(function overloading)</strong>: 매개변수가 다른 동일명 함수</li>
<li><strong>new와 delete</strong>: 동적 메모리 할당/해제</li>
<li><strong>제네릭(generics)</strong>: 자료형에 상관없이 재사용</li>
</ol>
<h3 id="설계-철학">설계 철학</h3>
<ul>
<li>엄격한 타입 검사, 효율적</li>
<li>범용 언어, 이식성</li>
<li>다양한 프로그래밍 스타일 지원 (절차지향, 객체지향, 일반화)</li>
<li>C와의 최대 호환성</li>
</ul>
<hr>
<h2 id="💻-2-기본-프로그램-구조">💻 2. 기본 프로그램 구조</h2>
<h3 id="표준-프로그램-템플릿">표준 프로그램 템플릿</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main()
{
    // 프로그램 내용
    return 0;
}
</code></pre>
<h3 id="핵심-구성-요소">핵심 구성 요소</h3>
<ul>
<li><code>#include &lt;iostream&gt;</code>: 입출력 스트림 헤더 포함</li>
<li><strong><code>using namespace std;</code>: std 네임스페이스 사용 선언</strong></li>
<li><code>int main()</code>: 프로그램의 시작점</li>
<li><code>return 0;</code>: 정상 종료 신호</li>
</ul>
<h3 id="주석comment">주석(Comment)</h3>
<pre><code class="language-cpp">// 한 줄 주석
/*
   여러 줄 주석
   블록 주석
*/
</code></pre>
<ul>
<li><strong>단축키</strong>: Ctrl+K, Ctrl+C (주석), Ctrl+K, Ctrl+U (주석 해제)</li>
</ul>
<hr>
<h2 id="🔢-3-변수와-자료형이건알아">🔢 3. 변수와 자료형/이건알아</h2>
<h3 id="기본-자료형">기본 자료형</h3>
<h3 id="정수형">정수형</h3>
<pre><code class="language-cpp">int age = 25;           // 4바이트
short height = 170;     // 2바이트
long population = 50000000L; // 4바이트 이상
</code></pre>
<h3 id="실수형">실수형</h3>
<pre><code class="language-cpp">float pi = 3.14f;       // 4바이트
double precision = 3.141592653; // 8바이트
</code></pre>
<h3 id="논리형">논리형</h3>
<pre><code class="language-cpp">bool isStudent = true;  // 1바이트
bool isWorking = false;
</code></pre>
<h3 id="문자형">문자형</h3>
<pre><code class="language-cpp">char grade = &#39;A&#39;;       // 1바이트
</code></pre>
<h3 id="문자열">문자열</h3>
<pre><code class="language-cpp">#include &lt;string&gt;
string name = &quot;홍길동&quot;;
string greeting = &quot;Hello&quot; + &quot; &quot; + &quot;World!&quot;;//걍 한번에 띄어쓰기있이 붙여써도됨 왜 이따구로햇는지모르겟네?
string number_str = to_string(123); // 숫자를 문자열로 변환
</code></pre>
<h3 id="기호상수">기호상수</h3>
<pre><code class="language-cpp">const double PI = 3.141592;
const int MAX_SIZE = 100;
</code></pre>
<h3 id="auto-키워드-자동-타입-추론">auto 키워드 (자동 타입 추론)</h3>
<pre><code class="language-cpp">auto number = 42;        // int로 추론
auto price = 99.99;      // double로 추론
auto name = &quot;김철수&quot;;     // const char*로 추론
</code></pre>
<hr>
<h2 id="📥📤-4-입력과-출력">📥📤 4. 입력과 출력</h2>
<h3 id="🔹-연산자-해석">🔹 연산자 해석</h3>
<ul>
<li><p><code>&lt;&lt;</code> : <strong>삽입 연산자 (insertion operator)</strong></p>
<p>  👉 <code>cout &lt;&lt; &quot;어쩌구&quot;;</code></p>
<p>  = <code>&quot;어쩌구&quot;</code>라는 데이터를 <strong>출력 스트림에 집어넣는다</strong> → 화면에 표시됨.</p>
</li>
<li><p><code>&gt;&gt;</code> : <strong>추출 연산자 (extraction operator)</strong></p>
<p>  👉 <code>cin &gt;&gt; 변수명;</code></p>
<p>  = 입력 스트림에서 데이터를 <strong>꺼내서 변수에 저장한다</strong>.</p>
</li>
</ul>
<h3 id="🔹-비유">🔹 비유</h3>
<ul>
<li><code>cout &lt;&lt;</code> : <strong>&quot;데이터를 파이프(스트림)에 흘려보낸다 → 밖(모니터)로 간다&quot;</strong></li>
<li><code>cin &gt;&gt;</code> : <strong>&quot;파이프(스트림)에서 데이터를 꺼낸다 → 내 변수로 가져온다&quot;</strong></li>
</ul>
<h3 id="출력-cout">출력 (cout)</h3>
<pre><code class="language-cpp">cout &lt;&lt; &quot;문자열 출력&quot;;
cout &lt;&lt; 변수명;
cout &lt;&lt; &quot;값: &quot; &lt;&lt; 변수 &lt;&lt; endl;
</code></pre>
<h3 id="입력-cin">입력 (cin)</h3>
<pre><code class="language-cpp">int age;
cin &gt;&gt; age;

string name;
cin &gt;&gt; name;  // 공백 전까지만 입력받음

// 여러 값 한번에 입력
int a, b;
cin &gt;&gt; a &gt;&gt; b;
</code></pre>
<h3 id="실용-예제">실용 예제</h3>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

int main() {
    string name;
    int age;

    cout &lt;&lt; &quot;이름을 입력하세요: &quot;;
    cin &gt;&gt; name;
    cout &lt;&lt; &quot;나이를 입력하세요: &quot;;
    cin &gt;&gt; age;

    cout &lt;&lt; name &lt;&lt; &quot;님의 나이는 &quot; &lt;&lt; age &lt;&lt; &quot;세입니다.&quot; &lt;&lt; endl;
    return 0;
}
</code></pre>
<hr>
<h2 id="🔢-5-연산자와-수식">🔢 5. 연산자와 수식</h2>
<h3 id="산술-연산자">산술 연산자</h3>
<pre><code class="language-cpp">int a = 10, b = 3;
cout &lt;&lt; a + b;  // 13 (덧셈)
cout &lt;&lt; a - b;  // 7  (뺄셈)
cout &lt;&lt; a * b;  // 30 (곱셈)
cout &lt;&lt; a / b;  // 3  (나눗셈 - 정수)
cout &lt;&lt; a % b;  // 1  (나머지)
</code></pre>
<h3 id="비교-연산자">비교 연산자</h3>
<blockquote>
<p>&#39;bool&#39;은 <strong>컴퓨터 프로그래밍에서 참(true)과 거짓(false)이라는 두 가지 값만 저장하는 논리 자료형(boolean type)을 의미</strong>하며, 영국 수학자 조지 불(George Boole)의 이름에서 유래했습니다. 이 자료형은 조건문이나 반복문에서 특정 상태를 참 또는 거짓으로 판단하여 제어하는 데 사용됩니다.</p>
</blockquote>
<pre><code class="language-cpp">int x = 5, y = 3;
bool result1 = (x &gt; y);   // true
bool result2 = (x == y);  // false
bool result3 = (x != y);  // true
</code></pre>
<hr>
<h2 id="🎲-6-난수-생성">🎲 6. 난수 생성</h2>
<h3 id="전통적인-방법">전통적인 방법</h3>
<pre><code class="language-cpp">#include &lt;ctime&gt;
#include &lt;cstdlib&gt;

srand(time(NULL));        // 시드값 초기화
int dice = (rand() % 6) + 1;  // 1~6 사이 난수
</code></pre>
<hr>
<h2 id="📝-예상-문제-및-풀이">📝 예상 문제 및 풀이</h2>
<h3 id="📌-문제-1-기본-개념-객관식">📌 문제 1: 기본 개념 (객관식)</h3>
<p><strong>C++의 개발자와 개발 장소는?</strong></p>
<ol>
<li>Dennis Ritchie, AT&amp;T 벨연구소</li>
<li>Bjarne Stroustrup, AT&amp;T 벨연구소</li>
<li>James Gosling, Sun Microsystems</li>
<li>Anders Hejlsberg, Microsoft</li>
</ol>
<p><strong>정답</strong>: 2번</p>
<hr>
<h3 id="📌-문제-2-프로그램-구조-단답형">📌 문제 2: 프로그램 구조 (단답형)</h3>
<p><strong>다음 빈칸을 채우시오.</strong></p>
<pre><code class="language-cpp">_______ &lt;iostream&gt;
_______ namespace std;

int _______()
{
    cout &lt;&lt; &quot;Hello World!&quot; &lt;&lt; _______;
    _______ 0;
}
</code></pre>
<p><strong>정답</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main()
{
    cout &lt;&lt; &quot;Hello World!&quot; &lt;&lt; endl;
    return 0;
}
</code></pre>
<hr>
<h3 id="📌-문제-3-변수와-자료형-서술형">📌 문제 3: 변수와 자료형 (서술형)</h3>
<p><strong>다음 변수 선언에서 잘못된 부분을 찾고 올바르게 수정하시오.</strong></p>
<pre><code class="language-cpp">int 2number = 100;
char name = &quot;홍길동&quot;;
bool isTrue = 1;
const PI = 3.14;
</code></pre>
<p><strong>정답</strong>:</p>
<pre><code class="language-cpp">int number2 = 100;        // 변수명은 숫자로 시작할 수 없음
string name = &quot;홍길동&quot;;    // 문자열은 string 타입 사용
bool isTrue = true;       // bool은 true/false 사용 권장
const double PI = 3.14;   // const는 타입 명시 필요
</code></pre>
<hr>
<h3 id="📌-문제-4-입출력-프로그래밍-실습형">📌 문제 4: 입출력 프로그래밍 (실습형)</h3>
<p><strong>사용자로부터 두 정수를 입력받아 사칙연산 결과를 모두 출력하는 프로그램을 작성하시오.</strong></p>
<p><strong>정답</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    int a, b;
    cout &lt;&lt; &quot;두 정수를 입력하세요: &quot;;
    cin &gt;&gt; a &gt;&gt; b;

    cout &lt;&lt; a &lt;&lt; &quot; + &quot; &lt;&lt; b &lt;&lt; &quot; = &quot; &lt;&lt; a + b &lt;&lt; endl;
    cout &lt;&lt; a &lt;&lt; &quot; - &quot; &lt;&lt; b &lt;&lt; &quot; = &quot; &lt;&lt; a - b &lt;&lt; endl;
    cout &lt;&lt; a &lt;&lt; &quot; * &quot; &lt;&lt; b &lt;&lt; &quot; = &quot; &lt;&lt; a * b &lt;&lt; endl;
    cout &lt;&lt; a &lt;&lt; &quot; / &quot; &lt;&lt; b &lt;&lt; &quot; = &quot; &lt;&lt; a / b &lt;&lt; endl;
    cout &lt;&lt; a &lt;&lt; &quot; % &quot; &lt;&lt; b &lt;&lt; &quot; = &quot; &lt;&lt; a % b &lt;&lt; endl;

    return 0;
}
</code></pre>
<hr>
<h3 id="📌-문제-5-실전-응용-복합형">📌 문제 5: 실전 응용 (복합형)</h3>
<p><strong>다음 조건을 만족하는 프로그램을 작성하시오:</strong></p>
<ul>
<li>사용자로부터 반지름을 입력받는다</li>
<li>원의 넓이와 둘레를 계산한다</li>
<li>결과를 소수점 둘째자리까지 출력한다</li>
</ul>
<p><strong>정답</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;iomanip&gt;
using namespace std;

int main() {
    const double PI = 3.141592;
    double radius;

    cout &lt;&lt; &quot;원의 반지름을 입력하세요: &quot;;
    cin &gt;&gt; radius;

    double area = PI * radius * radius;
    double circumference = 2 * PI * radius;

    cout &lt;&lt; fixed &lt;&lt; setprecision(2);
    cout &lt;&lt; &quot;원의 넓이: &quot; &lt;&lt; area &lt;&lt; endl;
    cout &lt;&lt; &quot;원의 둘레: &quot; &lt;&lt; circumference &lt;&lt; endl;

    return 0;
}
</code></pre>
<hr>
<h3 id="📌-문제-6-오류-찾기-디버깅">📌 문제 6: 오류 찾기 (디버깅)</h3>
<p><strong>다음 프로그램의 오류를 찾아 수정하시오.</strong></p>
<pre><code class="language-cpp">#include iostream
using namespace std

int main()
{
    int age
    cout &lt;&lt; &quot;나이를 입력하세요: &quot;
    cin &gt;&gt; age
    cout &lt;&lt; &quot;당신의 나이는 &quot; &lt;&lt; age &lt;&lt; &quot;세입니다.&quot; &lt;&lt; endl
    return 0
}
</code></pre>
<p><strong>정답 (수정된 코드)</strong>:</p>
<pre><code class="language-cpp">#include &lt;iostream&gt;     // &lt; &gt; 누락
using namespace std;    // 세미콜론 누락

int main()
{
    int age;            // 세미콜론 누락
    cout &lt;&lt; &quot;나이를 입력하세요: &quot;;  // 세미콜론 누락
    cin &gt;&gt; age;         // 세미콜론 누락
    cout &lt;&lt; &quot;당신의 나이는 &quot; &lt;&lt; age &lt;&lt; &quot;세입니다.&quot; &lt;&lt; endl;  // 세미콜론 누락
    return 0;           // 세미콜론 누락
}
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter13. 객체지향+, GUI 프로그래밍]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter13.-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A5-GUI-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-4z4v4cab</link>
            <guid>https://velog.io/@lullaby_/PythonChapter13.-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A5-GUI-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-4z4v4cab</guid>
            <pubDate>Wed, 01 Oct 2025 01:30:19 GMT</pubDate>
            <description><![CDATA[<h2 id="1-객체지향-프로그래밍-핵심-개념">1. 객체지향 프로그래밍 핵심 개념</h2>
<h3 id="11-클래스class와-객체object">1.1 클래스(Class)와 객체(Object)</h3>
<ul>
<li><strong>클래스</strong>: 객체를 만들기 위한 템플릿/설계도</li>
<li><strong>객체</strong>: 클래스의 인스턴스, 실제로 메모리에 할당된 실체</li>
</ul>
<pre><code class="language-python"># 기본 클래스 정의 예시
class Rectangle:
    def __init__(self, side=0):  # 생성자 메서드
        self.side = side  # 인스턴스 변수

    def getArea(self):  # 인스턴스 메서드
        return self.side * self.side

# 객체 생성
myRect = Rectangle(5)
print(myRect.getArea())  # 25</code></pre>
<h3 id="12-클래스-변수와-인스턴스-변수">1.2 클래스 변수와 인스턴스 변수</h3>
<ul>
<li><strong>클래스 변수</strong>: 클래스 내부에서 선언되며 모든 객체가 공유하는 변수</li>
<li><strong>인스턴스 변수</strong>: <code>self.변수명</code>으로 선언되며 각 객체마다 별도로 생성되는 변수</li>
</ul>
<pre><code class="language-python">class Television:
    serialNumber = 0  # 클래스 변수

    def __init__(self):
        Television.serialNumber += 1  # 클래스 변수 접근
        self.number = Television.serialNumber  # 인스턴스 변수

a = Television()
b = Television()
c = Television()

print(a.serialNumber)  # 3 (모든 객체가 공유)
print(a.number)  # 1 (객체별 고유값)
print(b.number)  # 2
print(c.number)  # 3
</code></pre>
<h3 id="13-특수-메서드special-methods">1.3 특수 메서드(Special Methods)</h3>
<p><img src="attachment:400cd23b-e732-4b01-a975-d2a68ee4b60b:image.png" alt="image.png"></p>
<ul>
<li><code>__init__</code>: 생성자 메서드</li>
<li><code>__eq__</code>: 두 객체의 동등성 비교 (== 연산자)</li>
<li><code>__lt__</code>: 크기 비교 (&lt; 연산자)</li>
<li><code>__add__</code>, <code>__sub__</code> 등: 산술 연산자 오버로딩</li>
</ul>
<pre><code class="language-python">class Circle:
    def __init__(self, radius):
        self.radius = radius

    def __eq__(self, other):
        return self.radius == other.radius

    def __lt__(self, other):
        return self.radius &lt; other.radius

c1 = Circle(10)
c2 = Circle(100)

print(c1 == c2)  # False
print(c1 &lt; c2)   # True
</code></pre>
<h3 id="14-벡터-연산-예제">1.4 벡터 연산 예제</h3>
<pre><code class="language-python">class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector2D(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Vector2D(self.x - other.x, self.y - other.y)

    def __str__(self):
        return &#39;(%d, %d)&#39; % (self.x, self.y)

u = Vector2D(0, 1)
v = Vector2D(1, 1)
result = u + v
print(result)  # (1, 2)
</code></pre>
<h2 id="2-gui-프로그래밍-핵심-개념">2. GUI 프로그래밍 핵심 개념</h2>
<h3 id="21-tkinter-기본-구조">2.1 tkinter 기본 구조</h3>
<pre><code class="language-python">from tkinter import *

window = Tk()  # 윈도우 생성
# 위젯 배치
window.mainloop()  # 이벤트 루프 시작
</code></pre>
<h3 id="22-주요-위젯">2.2 주요 위젯</h3>
<p><img src="attachment:51ed0dd9-369c-49c7-b9b7-b5462681bb6d:image.png" alt="image.png"></p>
<table>
<thead>
<tr>
<th>위젯</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td>Label</td>
<td>텍스트나 이미지 표시</td>
</tr>
<tr>
<td>Button</td>
<td>클릭 가능한 버튼</td>
</tr>
<tr>
<td>Entry</td>
<td>한 줄 텍스트 입력 필드</td>
</tr>
<tr>
<td>Text</td>
<td>여러 줄 텍스트 표시/편집</td>
</tr>
<tr>
<td>Frame</td>
<td>다른 위젯을 그룹화하는 컨테이너</td>
</tr>
<tr>
<td>Canvas</td>
<td>그래픽 그리기 위한 영역</td>
</tr>
</tbody></table>
<h3 id="23-위젯-배치-관리자">2.3 위젯 배치 관리자</h3>
<ul>
<li><strong>pack()</strong>: 상대적 위치로 배치 (TOP, BOTTOM, LEFT, RIGHT)</li>
<li><strong>grid()</strong>: 격자 형태로 배치 (row, column)</li>
<li><strong>place()</strong>: 절대 위치로 배치 (x, y)</li>
</ul>
<pre><code class="language-python"># pack() 예시
label = Label(window, text=&quot;Hello&quot;)
label.pack(side=LEFT)

# grid() 예시
label1 = Label(window, text=&quot;이름&quot;)
label1.grid(row=0, column=0)
entry1 = Entry(window)
entry1.grid(row=0, column=1)
</code></pre>
<h3 id="24-이벤트-처리">2.4 이벤트 처리</h3>
<pre><code class="language-python">def callback():
    button[&quot;text&quot;] = &quot;버튼이 클릭되었음!&quot;

button = Button(window, text=&quot;클릭&quot;, command=callback)
</code></pre>
<h3 id="25-계산기-예제-코어-로직">2.5 계산기 예제 (코어 로직)</h3>
<pre><code class="language-python">from tkinter import *

def click(key):
    if key == &#39;=&#39;:  # &#39;=&#39; 버튼이면 수식을 계산하여 결과를 표시
        try:
            result = eval(entry.get())
            entry.delete(0, END)  # 0번째 위치부터 끝까지 삭제
            entry.insert(END, str(result))
        except:
            entry.insert(END, &quot;오류!&quot;)
    elif key == &#39;C&#39;:
        entry.delete(0, END)
    else:
        entry.insert(END, key)

window = Tk()
window.title(&quot;계산기&quot;)

buttons = [&#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;+&#39;, &#39;C&#39;,
           &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;-&#39;, &#39; &#39;,
           &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;*&#39;, &#39; &#39;,
           &#39;0&#39;, &#39;.&#39;, &#39;=&#39;, &#39;/&#39;, &#39; &#39;]

# 반복문으로 버튼을 생성한다.
i = 0
for b in buttons:
    b = Button(window, text=b, width=5, relief=&#39;ridge&#39;, command=lambda x=b: click(x))
    b.grid(row=i//5+1, column=i%5)
    i += 1

# 엔트리 위젯은 5개의 셀을 병합한 너비로 맨 위에 배치된다.
entry = Entry(window, width=33, bg=&quot;yellow&quot;)
entry.grid(row=0, column=0, columnspan=5)

window.mainloop()</code></pre>
<h2 id="3-예상-문제-및-풀이">3. 예상 문제 및 풀이</h2>
<h1 id="파이썬-기말고사-대비-예상-문제-및-풀이">파이썬 기말고사 대비 예상 문제 및 풀이</h1>
<h2 id="객체지향-프로그래밍">객체지향 프로그래밍</h2>
<h3 id="문제-1-클래스와-객체-기초">문제 1: 클래스와 객체 기초</h3>
<p>다음 코드의 실행 결과는 무엇인가?</p>
<pre><code class="language-python">class Counter:
    count = 0

    def __init__(self):
        Counter.count += 1
        self.id = Counter.count

    def get_id(self):
        return self.id

a = Counter()
b = Counter()
print(a.count, b.count)
print(a.id, b.id)
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code>2 2
1 2
</code></pre><p>클래스 변수 <code>count</code>는 모든 객체가 공유하므로 두 객체 모두 2가 출력됩니다.
인스턴스 변수 <code>id</code>는 각 객체마다 다른 값을 가지므로 a는 1, b는 2가 출력됩니다.</p>
<h3 id="문제-2-특수-메서드">문제 2: 특수 메서드</h3>
<p>다음 코드를 실행했을 때 에러가 발생하지 않도록 <code>__lt__</code> 메서드를 구현하시오.</p>
<pre><code class="language-python">class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    # 여기에 __lt__ 메서드를 구현하세요

students = [Student(&quot;Kim&quot;, 85), Student(&quot;Lee&quot;, 92), Student(&quot;Park&quot;, 78)]
sorted_students = sorted(students)
for student in sorted_students:
    print(f&quot;{student.name}: {student.score}&quot;)
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def __lt__(self, other):
    return self.score &lt; other.score
</code></pre>
<h3 id="문제-3-벡터-연산">문제 3: 벡터 연산</h3>
<p>2차원 벡터를 나타내는 <code>Vector2D</code> 클래스에 곱셈 연산(<code>*</code>)을 지원하도록 <code>__mul__</code> 메서드를 구현하시오. 벡터와 스칼라 값의 곱셈을 지원해야 합니다.</p>
<pre><code class="language-python">class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f&quot;({self.x}, {self.y})&quot;

    # 여기에 __mul__ 메서드를 구현하세요

v = Vector2D(3, 4)
result = v * 2
print(result)  # 출력: (6, 8)
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def __mul__(self, scalar):
    return Vector2D(self.x * scalar, self.y * scalar)
</code></pre>
<h2 id="gui-프로그래밍">GUI 프로그래밍</h2>
<h3 id="문제-4-버튼-이벤트-처리">문제 4: 버튼 이벤트 처리</h3>
<p>다음 코드에서 버튼을 클릭할 때마다 카운터가 증가하도록 <code>increase_counter</code> 함수를 구현하시오.</p>
<pre><code class="language-python">from tkinter import *

def increase_counter():
    # 여기에 코드를 구현하세요

window = Tk()
counter = 0
label = Label(window, text=&quot;카운터: 0&quot;)
label.pack()

button = Button(window, text=&quot;증가&quot;, command=increase_counter)
button.pack()

window.mainloop()
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def increase_counter():
    global counter
    counter += 1
    label.config(text=f&quot;카운터: {counter}&quot;)
</code></pre>
<h3 id="문제-5-entry-위젯-활용">문제 5: Entry 위젯 활용</h3>
<p>다음 조건을 만족하는 간단한 온도 변환기(섭씨→화씨) GUI 프로그램의 <code>convert</code> 함수를 완성하시오.</p>
<pre><code class="language-python">from tkinter import *

def convert():
    # 여기에 코드를 구현하세요

window = Tk()
window.title(&quot;온도 변환기&quot;)

Label(window, text=&quot;섭씨(°C):&quot;).grid(row=0, column=0)
celsius_entry = Entry(window)
celsius_entry.grid(row=0, column=1)

Label(window, text=&quot;화씨(°F):&quot;).grid(row=1, column=0)
fahrenheit_label = Label(window, text=&quot;&quot;)
fahrenheit_label.grid(row=1, column=1)

Button(window, text=&quot;변환&quot;, command=convert).grid(row=2, column=1)

window.mainloop()
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def convert():
    try:
        celsius = float(celsius_entry.get())
        fahrenheit = (celsius * 9/5) + 32
        fahrenheit_label.config(text=f&quot;{fahrenheit:.2f}&quot;)
    except ValueError:
        fahrenheit_label.config(text=&quot;오류: 숫자를 입력하세요&quot;)
</code></pre>
<h3 id="문제-6-산수-퀴즈-프로그램">문제 6: 산수 퀴즈 프로그램</h3>
<p>다음 산수 퀴즈 프로그램에서 <code>check_answer</code> 함수를 완성하여, 사용자의 답을 확인하고 결과를 표시하시오.</p>
<pre><code class="language-python">from tkinter import *
import random

def generate_question():
    global a, b, operation
    a = random.randint(1, 10)
    b = random.randint(1, 10)
    operation = random.choice([&#39;+&#39;, &#39;-&#39;, &#39;*&#39;])
    question_label.config(text=f&quot;{a} {operation} {b} = ?&quot;)
    answer_entry.delete(0, END)
    result_label.config(text=&quot;&quot;)

def check_answer():
    # 여기에 코드를 구현하세요

window = Tk()
window.title(&quot;산수 퀴즈&quot;)

a, b, operation = 0, 0, &#39;+&#39;

question_label = Label(window, font=(&#39;Arial&#39;, 14))
question_label.pack(pady=10)

answer_entry = Entry(window)
answer_entry.pack(pady=5)

Button(window, text=&quot;확인&quot;, command=check_answer).pack(pady=5)
Button(window, text=&quot;새 문제&quot;, command=generate_question).pack(pady=5)

result_label = Label(window, font=(&#39;Arial&#39;, 12))
result_label.pack(pady=10)

generate_question()
window.mainloop()
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def check_answer():
    try:
        user_answer = int(answer_entry.get())
        if operation == &#39;+&#39;:
            correct_answer = a + b
        elif operation == &#39;-&#39;:
            correct_answer = a - b
        else:  # &#39;*&#39;
            correct_answer = a * b

        if user_answer == correct_answer:
            result_label.config(text=&quot;정답입니다!&quot;, fg=&quot;green&quot;)
        else:
            result_label.config(text=f&quot;오답입니다. 정답은 {correct_answer}입니다.&quot;, fg=&quot;red&quot;)
    except ValueError:
        result_label.config(text=&quot;숫자를 입력하세요&quot;, fg=&quot;red&quot;)
</code></pre>
<h1 id="파이썬-객체지향-프로그래밍--gui-기말고사-대비-요약-정리">파이썬 객체지향 프로그래밍 &amp; GUI 기말고사 대비 요약 정리</h1>
<h2 id="객체지향-프로그래밍-1">객체지향 프로그래밍</h2>
<h3 id="1-객체와-클래스의-기본-개념">1. 객체와 클래스의 기본 개념</h3>
<ul>
<li><strong>클래스(Class)</strong>: 객체를 생성하기 위한 템플릿/설계도</li>
<li><strong>객체(Object)</strong>: 클래스의 인스턴스(실체)</li>
<li><strong>속성(Attribute)</strong>: 객체의 특성을 나타내는 변수</li>
<li><strong>메서드(Method)</strong>: 객체가 수행할 수 있는 동작/함수</li>
</ul>
<pre><code class="language-python"># 기본 클래스 구조
class ClassName:
    # 생성자 메서드
    def __init__(self, parameter1, parameter2):
        self.attribute1 = parameter1  # 인스턴스 변수
        self.attribute2 = parameter2

    # 일반 메서드
    def method1(self):
        # 메서드 내용
        pass
</code></pre>
<h3 id="2-변수-유형">2. 변수 유형</h3>
<table>
<thead>
<tr>
<th>변수 유형</th>
<th>설명</th>
<th>예제</th>
</tr>
</thead>
<tbody><tr>
<td>클래스 변수</td>
<td>모든 객체가 공유하는 변수</td>
<td><code>ClassName.variable</code></td>
</tr>
<tr>
<td>인스턴스 변수</td>
<td>각 객체마다 독립적인 변수</td>
<td><code>self.variable</code></td>
</tr>
<tr>
<td>지역 변수</td>
<td>메서드 내에서만 사용 가능한 변수</td>
<td><code>variable</code></td>
</tr>
</tbody></table>
<pre><code class="language-python">class Television:
    serialNumber = 0  # 클래스 변수

    def __init__(self):
        Television.serialNumber += 1
        self.number = Television.serialNumber  # 인스턴스 변수

    def display(self):
        count = 1  # 지역 변수
        print(f&quot;TV #{self.number}, 총 TV 개수: {Television.serialNumber}&quot;)
</code></pre>
<h3 id="3-특수-메서드magic-methods">3. 특수 메서드(Magic Methods)</h3>
<table>
<thead>
<tr>
<th>메서드</th>
<th>연산자</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><code>__init__(self, ...)</code></td>
<td>-</td>
<td>객체 초기화(생성자)</td>
</tr>
<tr>
<td><code>__str__(self)</code></td>
<td><code>str()</code></td>
<td>문자열 표현 반환</td>
</tr>
<tr>
<td><code>__eq__(self, other)</code></td>
<td><code>==</code></td>
<td>동등성 비교</td>
</tr>
<tr>
<td><code>__lt__(self, other)</code></td>
<td><code>&lt;</code></td>
<td>작음 비교</td>
</tr>
<tr>
<td><code>__add__(self, other)</code></td>
<td><code>+</code></td>
<td>덧셈</td>
</tr>
<tr>
<td><code>__sub__(self, other)</code></td>
<td><code>-</code></td>
<td>뺄셈</td>
</tr>
<tr>
<td><code>__mul__(self, other)</code></td>
<td><code>*</code></td>
<td>곱셈</td>
</tr>
<tr>
<td><code>__truediv__(self, other)</code></td>
<td><code>/</code></td>
<td>나눗셈</td>
</tr>
<tr>
<td><code>__floordiv__(self, other)</code></td>
<td><code>//</code></td>
<td>정수 나눗셈</td>
</tr>
<tr>
<td><code>__mod__(self, other)</code></td>
<td><code>%</code></td>
<td>나머지</td>
</tr>
</tbody></table>
<pre><code class="language-python">class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f&quot;({self.x}, {self.y})&quot;

    def __add__(self, other):
        return Vector2D(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Vector2D(self.x - other.x, self.y - other.y)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
</code></pre>
<h3 id="4-객체와-함수의-관계">4. 객체와 함수의 관계</h3>
<pre><code class="language-python">class Rectangle:
    def __init__(self, side=0):
        self.side = side

    def getArea(self):
        return self.side * self.side

# 객체를 함수에 전달
def printAreas(r, n):
    while n &gt;= 1:
        print(f&quot;n = {n}, r.side = {r.side}, r.getArea() = {r.getArea()}&quot;)
        r.side = r.side + 1
        n = n - 1

# 함수 호출
myRect = Rectangle()
count = 5
printAreas(myRect, count)
print(f&quot;함수 탈출 후 myRect.side = {myRect.side}&quot;)  # 5
</code></pre>
<h2 id="gui-프로그래밍-tkinter">GUI 프로그래밍 (tkinter)</h2>
<h3 id="1-tkinter-기본-구조">1. tkinter 기본 구조</h3>
<pre><code class="language-python">from tkinter import *

window = Tk()  # 윈도우 생성
window.title(&quot;제목&quot;)  # 윈도우 제목 설정

# 위젯 배치 코드

window.mainloop()  # 이벤트 루프 시작
</code></pre>
<h3 id="2-주요-위젯">2. 주요 위젯</h3>
<table>
<thead>
<tr>
<th>위젯</th>
<th>설명</th>
<th>생성 예시</th>
</tr>
</thead>
<tbody><tr>
<td>Label</td>
<td>텍스트/이미지 표시</td>
<td><code>Label(window, text=&quot;텍스트&quot;)</code></td>
</tr>
<tr>
<td>Button</td>
<td>클릭 가능한 버튼</td>
<td><code>Button(window, text=&quot;버튼&quot;, command=함수명)</code></td>
</tr>
<tr>
<td>Entry</td>
<td>한 줄 텍스트 입력</td>
<td><code>Entry(window)</code></td>
</tr>
<tr>
<td>Text</td>
<td>여러 줄 텍스트 입력/표시</td>
<td><code>Text(window, height=5, width=30)</code></td>
</tr>
<tr>
<td>Frame</td>
<td>다른 위젯 그룹화</td>
<td><code>Frame(window)</code></td>
</tr>
<tr>
<td>Canvas</td>
<td>그래픽 그리기</td>
<td><code>Canvas(window, width=300, height=200)</code></td>
</tr>
<tr>
<td>Checkbutton</td>
<td>체크박스</td>
<td><code>Checkbutton(window, text=&quot;체크&quot;)</code></td>
</tr>
<tr>
<td>Radiobutton</td>
<td>라디오 버튼</td>
<td><code>Radiobutton(window, text=&quot;옵션&quot;)</code></td>
</tr>
<tr>
<td>Listbox</td>
<td>선택 목록</td>
<td><code>Listbox(window)</code></td>
</tr>
<tr>
<td>Scrollbar</td>
<td>스크롤바</td>
<td><code>Scrollbar(window)</code></td>
</tr>
<tr>
<td>Menu</td>
<td>메뉴</td>
<td><code>Menu(window)</code></td>
</tr>
<tr>
<td>PhotoImage</td>
<td>이미지 표시용</td>
<td><code>PhotoImage(file=&quot;이미지.gif&quot;)</code></td>
</tr>
</tbody></table>
<h3 id="3-배치-관리자">3. 배치 관리자</h3>
<table>
<thead>
<tr>
<th>배치 관리자</th>
<th>설명</th>
<th>예시</th>
</tr>
</thead>
<tbody><tr>
<td>pack()</td>
<td>상대적 위치로 배치</td>
<td><code>widget.pack(side=LEFT, padx=10, pady=5)</code></td>
</tr>
<tr>
<td>grid()</td>
<td>행과 열 기반 배치</td>
<td><code>widget.grid(row=0, column=1)</code></td>
</tr>
<tr>
<td>place()</td>
<td>절대 위치로 배치</td>
<td><code>widget.place(x=100, y=200)</code></td>
</tr>
</tbody></table>
<h3 id="pack-옵션">pack() 옵션</h3>
<ul>
<li><code>side</code>: TOP(기본값), BOTTOM, LEFT, RIGHT</li>
<li><code>fill</code>: X, Y, BOTH, NONE</li>
<li><code>expand</code>: 0(기본값) 또는 1</li>
<li><code>padx</code>, <code>pady</code>: 여백</li>
</ul>
<h3 id="grid-옵션">grid() 옵션</h3>
<ul>
<li><code>row</code>, <code>column</code>: 배치할 행과 열 (0부터 시작)</li>
<li><code>rowspan</code>, <code>columnspan</code>: 병합할 행/열 수</li>
<li><code>padx</code>, <code>pady</code>: 여백</li>
</ul>
<h3 id="4-이벤트-처리">4. 이벤트 처리</h3>
<pre><code class="language-python"># 방법 1: command 옵션 사용
def button_clicked():
    label.config(text=&quot;버튼이 클릭되었습니다!&quot;)

button = Button(window, text=&quot;클릭&quot;, command=button_clicked)

# 방법 2: bind() 메서드 사용
def key_pressed(event):
    print(f&quot;키가 눌렸습니다: {event.char}&quot;)

entry.bind(&quot;&lt;Key&gt;&quot;, key_pressed)
</code></pre>
<h3 id="5-위젯-속성-변경">5. 위젯 속성 변경</h3>
<pre><code class="language-python"># 생성 시 설정
label = Label(window, text=&quot;원래 텍스트&quot;, fg=&quot;blue&quot;, bg=&quot;yellow&quot;)

# 나중에 변경
label[&quot;text&quot;] = &quot;변경된 텍스트&quot;  # 딕셔너리 형태로 접근
label.config(text=&quot;새로운 텍스트&quot;, fg=&quot;red&quot;)  # config() 메서드 사용
</code></pre>
<h3 id="6-계산기-응용-프로그램">6. 계산기 응용 프로그램</h3>
<pre><code class="language-python">from tkinter import *

def click(key):
    if key == &#39;=&#39;:  # 계산 실행
        try:
            result = eval(entry.get())
            entry.delete(0, END)
            entry.insert(END, str(result))
        except:
            entry.insert(END, &quot;오류!&quot;)
    elif key == &#39;C&#39;:  # 입력 내용 지우기
        entry.delete(0, END)
    else:  # 다른 키는 화면에 추가
        entry.insert(END, key)

window = Tk()
window.title(&quot;계산기&quot;)

# 계산 결과 표시창
entry = Entry(window, width=33, bg=&quot;yellow&quot;)
entry.grid(row=0, column=0, columnspan=5)

# 버튼 배열 정의
buttons = [&#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;+&#39;, &#39;C&#39;,
           &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;-&#39;, &#39; &#39;,
           &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;*&#39;, &#39; &#39;,
           &#39;0&#39;, &#39;.&#39;, &#39;=&#39;, &#39;/&#39;, &#39; &#39;]

# 버튼 생성 및 배치
i = 0
for b in buttons:
    button = Button(window, text=b, width=5, relief=&#39;ridge&#39;,
                   command=lambda x=b: click(x))
    button.grid(row=i//5+1, column=i%5)
    i += 1
</code></pre>
<h2 id="자주-실수하는-부분과-주요-포인트">자주 실수하는 부분과 주요 포인트</h2>
<h3 id="객체지향-프로그래밍-2">객체지향 프로그래밍</h3>
<ol>
<li><code>self</code> 매개변수 누락: 모든 인스턴스 메서드의 첫 매개변수는 반드시 <code>self</code></li>
<li>클래스 변수와 인스턴스 변수 혼동: 용도에 맞게 사용</li>
<li>특수 메서드 구현 시 매개변수 개수/이름 확인: <code>__add__(self, other)</code></li>
</ol>
<h3 id="gui-프로그래밍-1">GUI 프로그래밍</h3>
<ol>
<li><code>mainloop()</code> 호출 누락: 이벤트 루프 시작을 위해 필수</li>
<li>위젯 생성과 배치 분리: <code>button = Button(...); button.pack()</code> 또는 <code>Button(...).pack()</code></li>
<li>전역 변수 사용 시 <code>global</code> 키워드 필요: 함수 내에서 전역 변수 변경 시</li>
<li>람다 함수 사용 시 매개변수 전달 주의: <code>command=lambda x=value: function(x)</code></li>
<li>이벤트 처리 함수에서 이벤트 객체(event) 처리: <code>bind</code> 사용 시 필요</li>
</ol>
<h2 id="예상-문제-및-풀이">예상 문제 및 풀이</h2>
<h1 id="파이썬-기말고사-대비-예상-문제-및-풀이-1">파이썬 기말고사 대비 예상 문제 및 풀이</h1>
<h2 id="객체지향-프로그래밍-3">객체지향 프로그래밍</h2>
<h3 id="문제-1-클래스와-객체-기초-1">문제 1: 클래스와 객체 기초</h3>
<p>다음 코드의 실행 결과는 무엇인가?</p>
<pre><code class="language-python">class Counter:
    count = 0

    def __init__(self):
        Counter.count += 1
        self.id = Counter.count

    def get_id(self):
        return self.id

a = Counter()
b = Counter()
print(a.count, b.count)
print(a.id, b.id)
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code>2 2
1 2
</code></pre><p>클래스 변수 <code>count</code>는 모든 객체가 공유하므로 두 객체 모두 2가 출력됩니다.
인스턴스 변수 <code>id</code>는 각 객체마다 다른 값을 가지므로 a는 1, b는 2가 출력됩니다.</p>
<h3 id="문제-2-특수-메서드-1">문제 2: 특수 메서드</h3>
<p>다음 코드를 실행했을 때 에러가 발생하지 않도록 <code>__lt__</code> 메서드를 구현하시오.</p>
<pre><code class="language-python">class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    # 여기에 __lt__ 메서드를 구현하세요

students = [Student(&quot;Kim&quot;, 85), Student(&quot;Lee&quot;, 92), Student(&quot;Park&quot;, 78)]
sorted_students = sorted(students)
for student in sorted_students:
    print(f&quot;{student.name}: {student.score}&quot;)
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def __lt__(self, other):
    return self.score &lt; other.score
</code></pre>
<h3 id="문제-3-벡터-연산-1">문제 3: 벡터 연산</h3>
<p>2차원 벡터를 나타내는 <code>Vector2D</code> 클래스에 곱셈 연산(<code>*</code>)을 지원하도록 <code>__mul__</code> 메서드를 구현하시오. 벡터와 스칼라 값의 곱셈을 지원해야 합니다.</p>
<pre><code class="language-python">class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f&quot;({self.x}, {self.y})&quot;

    # 여기에 __mul__ 메서드를 구현하세요

v = Vector2D(3, 4)
result = v * 2
print(result)  # 출력: (6, 8)
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def __mul__(self, scalar):
    return Vector2D(self.x * scalar, self.y * scalar)
</code></pre>
<h2 id="gui-프로그래밍-2">GUI 프로그래밍</h2>
<h3 id="문제-4-버튼-이벤트-처리-1">문제 4: 버튼 이벤트 처리</h3>
<p>다음 코드에서 버튼을 클릭할 때마다 카운터가 증가하도록 <code>increase_counter</code> 함수를 구현하시오.</p>
<pre><code class="language-python">from tkinter import *

def increase_counter():
    # 여기에 코드를 구현하세요

window = Tk()
counter = 0
label = Label(window, text=&quot;카운터: 0&quot;)
label.pack()

button = Button(window, text=&quot;증가&quot;, command=increase_counter)
button.pack()

window.mainloop()
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def increase_counter():
    global counter
    counter += 1
    label.config(text=f&quot;카운터: {counter}&quot;)
</code></pre>
<h3 id="문제-5-entry-위젯-활용-1">문제 5: Entry 위젯 활용</h3>
<p>다음 조건을 만족하는 간단한 온도 변환기(섭씨→화씨) GUI 프로그램의 <code>convert</code> 함수를 완성하시오.</p>
<pre><code class="language-python">from tkinter import *

def convert():
    # 여기에 코드를 구현하세요

window = Tk()
window.title(&quot;온도 변환기&quot;)

Label(window, text=&quot;섭씨(°C):&quot;).grid(row=0, column=0)
celsius_entry = Entry(window)
celsius_entry.grid(row=0, column=1)

Label(window, text=&quot;화씨(°F):&quot;).grid(row=1, column=0)
fahrenheit_label = Label(window, text=&quot;&quot;)
fahrenheit_label.grid(row=1, column=1)

Button(window, text=&quot;변환&quot;, command=convert).grid(row=2, column=1)

window.mainloop()
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def convert():
    try:
        celsius = float(celsius_entry.get())
        fahrenheit = (celsius * 9/5) + 32
        fahrenheit_label.config(text=f&quot;{fahrenheit:.2f}&quot;)
    except ValueError:
        fahrenheit_label.config(text=&quot;오류: 숫자를 입력하세요&quot;)
</code></pre>
<h3 id="문제-6-산수-퀴즈-프로그램-1">문제 6: 산수 퀴즈 프로그램</h3>
<p>다음 산수 퀴즈 프로그램에서 <code>check_answer</code> 함수를 완성하여, 사용자의 답을 확인하고 결과를 표시하시오.</p>
<pre><code class="language-python">from tkinter import *
import random

def generate_question():
    global a, b, operation
    a = random.randint(1, 10)
    b = random.randint(1, 10)
    operation = random.choice([&#39;+&#39;, &#39;-&#39;, &#39;*&#39;])
    question_label.config(text=f&quot;{a} {operation} {b} = ?&quot;)
    answer_entry.delete(0, END)
    result_label.config(text=&quot;&quot;)

def check_answer():
    # 여기에 코드를 구현하세요

window = Tk()
window.title(&quot;산수 퀴즈&quot;)

a, b, operation = 0, 0, &#39;+&#39;

question_label = Label(window, font=(&#39;Arial&#39;, 14))
question_label.pack(pady=10)

answer_entry = Entry(window)
answer_entry.pack(pady=5)

Button(window, text=&quot;확인&quot;, command=check_answer).pack(pady=5)
Button(window, text=&quot;새 문제&quot;, command=generate_question).pack(pady=5)

result_label = Label(window, font=(&#39;Arial&#39;, 12))
result_label.pack(pady=10)

generate_question()
window.mainloop()
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def check_answer():
    try:
        user_answer = int(answer_entry.get())
        if operation == &#39;+&#39;:
            correct_answer = a + b
        elif operation == &#39;-&#39;:
            correct_answer = a - b
        else:  # &#39;*&#39;
            correct_answer = a * b

        if user_answer == correct_answer:
            result_label.config(text=&quot;정답입니다!&quot;, fg=&quot;green&quot;)
        else:
            result_label.config(text=f&quot;오답입니다. 정답은 {correct_answer}입니다.&quot;, fg=&quot;red&quot;)
    except ValueError:
        result_label.config(text=&quot;숫자를 입력하세요&quot;, fg=&quot;red&quot;)
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter12. 객체지향, 클래스, 정보은닉과 캡슐화, 객체의 문자열표현]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter12.-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A5-%ED%81%B4%EB%9E%98%EC%8A%A4-%EC%A0%95%EB%B3%B4%EC%9D%80%EB%8B%89%EA%B3%BC-%EC%BA%A1%EC%8A%90%ED%99%94-%EA%B0%9D%EC%B2%B4%EC%9D%98-%EB%AC%B8%EC%9E%90%EC%97%B4%ED%91%9C%ED%98%84-bhir29ha</link>
            <guid>https://velog.io/@lullaby_/PythonChapter12.-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A5-%ED%81%B4%EB%9E%98%EC%8A%A4-%EC%A0%95%EB%B3%B4%EC%9D%80%EB%8B%89%EA%B3%BC-%EC%BA%A1%EC%8A%90%ED%99%94-%EA%B0%9D%EC%B2%B4%EC%9D%98-%EB%AC%B8%EC%9E%90%EC%97%B4%ED%91%9C%ED%98%84-bhir29ha</guid>
            <pubDate>Wed, 01 Oct 2025 01:28:59 GMT</pubDate>
            <description><![CDATA[<h2 id="1-객체지향의-기본-개념">1. 객체지향의 기본 개념</h2>
<h3 id="11-클래스와-객체">1.1 클래스와 객체</h3>
<ul>
<li><strong>클래스(Class)</strong>: 객체를 생성하기 위한 템플릿 또는 청사진</li>
<li><strong>객체(Object)</strong>: 클래스의 인스턴스, 실제 메모리에 할당된 실체</li>
<li><strong>인스턴스 변수</strong>: 각 객체마다 개별적으로 가지는 변수</li>
<li><strong>메소드</strong>: 클래스 내에 정의된 함수</li>
</ul>
<pre><code class="language-python">
python
class Counter:
    def __init__(self):
        self.count = 0

    def reset(self):
        self.count = 0

    def increment(self):
        self.count += 1

    def get(self):
        return self.count

# 객체 생성 및 사용
a = Counter()
print(a.count)# 0
a.increment()
print(a.count)# 1
print(a.get())# 1
</code></pre>
<h3 id="12-생성자-__init__">1.2 생성자 (<code>__init__</code>)</h3>
<ul>
<li><strong>객체가 생성될 때 자동으로 호출되는 특별한 메소드</strong></li>
<li>객체를 초기 상태로 설정하는 역할</li>
<li>첫 번째 매개변수는 항상 <code>self</code></li>
</ul>
<pre><code class="language-python">
python
class Television:
    def __init__(self, channel, volume, on):
        self.channel = channel
        self.volume = volume
        self.on = on

    def show(self):
        print(self.channel, self.volume, self.on)

    def setChannel(self, channel):
        self.channel = channel

    def getChannel(self):
        return self.channel

# 객체 생성 및 메소드 호출
t = Television(9, 10, True)
t.show()# 9 10 True
t.setChannel(11)
t.show()# 11 10 True
</code></pre>
<h3 id="13-기본값-매개변수">1.3 기본값 매개변수</h3>
<ul>
<li>생성자나 메소드의 매개변수에 기본값 설정 가능</li>
</ul>
<pre><code class="language-python">
python
class Student:
    def __init__(self, name=None, age=0):
        self.name = name
        self.age = age

ob1 = Student(&quot;Hong&quot;, 20)
print(&quot;object 1 상태 :&quot;, ob1.name, ob1.age)# object 1 상태 : Hong 20
ob2 = Student()
print(&quot;object 2 상태 :&quot;, ob2.name, ob2.age)# object 2 상태 : None 0
</code></pre>
<h2 id="2-정보-은닉과-캡슐화">2. 정보 은닉과 캡슐화</h2>
<h3 id="21-비공개-인스턴스-변수-private-variables">2.1 비공개 인스턴스 변수 (Private Variables)</h3>
<ul>
<li>변수명 앞에 이중 밑줄(<code>__</code>)을 붙여 정의</li>
<li>클래스 외부에서 직접 접근 불가</li>
<li>클래스 내부에서만 접근 가능</li>
</ul>
<pre><code class="language-python">
python
class Student:
    def __init__(self, name=None, age=0):
        self.__name = name# 비공개 인스턴스 변수
        self.__age = age# 비공개 인스턴스 변수

obj = Student(&quot;Hong&quot;, 20)
# print(obj.__age)    # 오류 발생: AttributeError
</code></pre>
<h3 id="22-접근자getter와-설정자setter-메소드">2.2 접근자(Getter)와 설정자(Setter) 메소드</h3>
<ul>
<li>비공개 인스턴스 변수에 안전하게 접근하고 수정하기 위한 메소드</li>
<li>값의 유효성 검사 등 로직 추가 가능</li>
</ul>
<pre><code class="language-python">
python
class Student:
    def __init__(self, name=None, age=0):
        self.__name = name
        self.__age = age

    def getAge(self):
        return self.__age

    def getName(self):
        return self.__name

    def setAge(self, age):
        self.__age = age

    def setName(self, name):
        self.__name = name

obj = Student(&quot;Hong&quot;, 20)
print(obj.getName())# Hong
obj.setAge(30)
print(obj.getAge())# 30
</code></pre>
<h3 id="23-명명-규칙에-의한-비공개-변수-접근-네임-맹글링">2.3 명명 규칙에 의한 비공개 변수 접근 (네임 맹글링)</h3>
<ul>
<li>실제로는 <code>_클래스명__변수명</code> 형태로 변환됨</li>
<li>이를 통해 비공개 변수에도 접근 가능 (하지만 권장되지 않음)</li>
</ul>
<pre><code class="language-python">
python
obj = Student(&quot;Hong&quot;, 20)
print(obj._Student__age)# 20
print(obj._Student__name)# Hong
</code></pre>
<h2 id="3-객체의-문자열-표현-__str__-메소드">3. 객체의 문자열 표현 (<code>__str__</code> 메소드)</h2>
<ul>
<li>객체를 문자열로 표현할 때 사용되는 특별 메소드</li>
<li><code>print(객체)</code> 호출 시 자동으로 사용됨</li>
</ul>
<pre><code class="language-python">
python
class Cat:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def __str__(self):
        return &#39;(%s, %d)&#39; % (self.__name, self.__age)

cream = Cat(&#39;Cream&#39;, 15)
print(cream)# (Cream, 15)
</code></pre>
<h2 id="4-실제-응용-예제">4. 실제 응용 예제</h2>
<h3 id="41-원circle-클래스">4.1 원(Circle) 클래스</h3>
<pre><code class="language-python">
python
import math

class Circle:
    def __init__(self, radius=1.0):
        self.__radius = radius

    def setRadius(self, r):
        self.__radius = r

    def getRadius(self):
        return self.__radius

    def calcArea(self):
        area = math.pi * self.__radius * self.__radius
        return area

    def calcCircum(self):
        circumference = 2.0 * math.pi * self.__radius
        return circumference

c1 = Circle(10)
print(&quot;원의 반지름=&quot;, c1.getRadius())
print(&quot;원의 넓이=&quot;, c1.calcArea())
print(&quot;원의 둘레=&quot;, c1.calcCircum())
</code></pre>
<h3 id="42-은행-계좌bankaccount-클래스">4.2 은행 계좌(BankAccount) 클래스</h3>
<pre><code class="language-python">
python
class BankAccount:
    def __init__(self):
        self.__balance = 0
        print(&quot;처음 잔액 :&quot;, self.__balance, &quot;\n&quot;)

    def withdraw(self, amount):
        self.__balance -= amount
        print(&quot;통장에&quot;, amount, &quot;원 출금되었음&quot;)
        return self.__balance

    def deposit(self, amount):
        self.__balance += amount
        print(&quot;통장에서&quot;, amount, &quot;원 입금되었음&quot;)
        return self.__balance

a = BankAccount()
print(&quot;현재 잔액 :&quot;, a.deposit(100000), &quot;원\n&quot;)
print(&quot;현재 잔액 :&quot;, a.withdraw(10000), &quot;원\n&quot;)
</code></pre>
<h3 id="43-상자box-클래스---부피-계산">4.3 상자(Box) 클래스 - 부피 계산</h3>
<pre><code class="language-python">
python
class Box:
    def __init__(self, length=0, width=0, height=0):
        self.__width = width
        self.__length = length
        self.__height = height

    def setLength(self, length):
        self.__length = length

    def setWidth(self, width):
        self.__width = width

    def setHeight(self, height):
        self.__height = height

    def getVolume(self):
        return self.__width * self.__length * self.__height

    def __str__(self):
        return &#39;(%d, %d, %d)&#39; % (self.__length, self.__width, self.__height)

box = Box(10, 4, 5)
print(box)# (10, 4, 5)
print(&#39;상자의 부피는&#39;, box.getVolume())# 상자의 부피는 200
</code></pre>
<h3 id="44-자동차car-클래스">4.4 자동차(Car) 클래스</h3>
<pre><code class="language-python">
python
class Car:
    def __init__(self, speed=0, gear=1, color=&quot;white&quot;):
        self.__speed = speed
        self.__gear = gear
        self.__color = color

    def setSpeed(self, speed):
        self.__speed = speed

    def setGear(self, gear):
        self.__gear = gear

    def setColor(self, color):
        self.__color = color

    def __str__(self):
        return &#39;(%d, %d, %s)&#39; % (self.__speed, self.__gear, self.__color)

myCar = Car()
print(myCar)# (0, 1, white)
myCar.setGear(3)
myCar.setSpeed(100)
print(myCar)# (100, 3, white)
</code></pre>
<h3 id="45-객체를-함수로-전달하기">4.5 객체를 함수로 전달하기</h3>
<pre><code class="language-python">
python
class Rectangle:
    def __init__(self, side=0):
        self.side = side

    def getArea(self):
        return self.side * self.side

# 사각형 객체와 반복횟수를 매개변수로 받는 함수
def printAreas(r, n):
    while n &gt;= 1:
        print(&quot;n =&quot;, n, &quot;이고&quot;, &quot;r.side =&quot;, r.side, &quot;r.getArea() =&quot;, r.getArea())
        r.side = r.side + 1
        n = n - 1

myRect = Rectangle()
count = 5
printAreas(myRect, count)
print(&quot;\n함수 탈출 후 myRect.side =&quot;, myRect.side)# 5
</code></pre>
<h2 id="5-기말고사-예상-문제">5. 기말고사 예상 문제</h2>
<h3 id="문제-1-기본-클래스-작성">문제 1: 기본 클래스 작성</h3>
<p><strong>문제</strong>: 다음 조건을 만족하는 <code>Person</code> 클래스를 작성하시오.</p>
<ul>
<li><p>인스턴스 변수: <code>__name</code>(이름), <code>__age</code>(나이)</p>
</li>
<li><p>생성자: 이름과 나이를 매개변수로 받아 초기화</p>
</li>
<li><p>접근자 메소드: <code>getName()</code>, <code>getAge()</code></p>
</li>
<li><p>설정자 메소드: <code>setName()</code>, <code>setAge()</code></p>
</li>
<li><p><code>__str__</code> 메소드: &quot;(이름, 나이)&quot; 형태로 반환</p>
</li>
<li><p>person 클래스 풀이</p>
<p>  class Person:</p>
<pre><code>  def __init__(self, name=None, age=0):
      self.__name = name
      self.__age = age

  def getName(self):
      return self.__name

  def getAge(self):
      return self.__age

  def setName(self, name):
      self.__name = name

  def setAge(self, age):
      self.__age = age

  def __str__(self):
      return &#39;(%s, %d)&#39; % (self.__name, self.__age)</code></pre><p>  <em># 테스트 코드</em></p>
<p>  person1 = Person(&quot;Kim&quot;, 25)
  print(person1)</p>
<p>  <em># (Kim, 25)</em></p>
<p>  print(person1.getName())</p>
<p>  <em># Kim</em></p>
<p>  print(person1.getAge())</p>
<p>  <em># 25</em></p>
<p>  person1.setName(&quot;Park&quot;)
  person1.setAge(30)
  print(person1)</p>
<p>  <em># (Park, 30)</em></p>
</li>
</ul>
<h1 id="파이썬-객체지향-프로그래밍-기말고사-대비-예상-문제">파이썬 객체지향 프로그래밍 기말고사 대비 예상 문제</h1>
<p>제공해주신 객체지향 방법론 학습 자료를 바탕으로 기말고사 대비용 예상 문제를 준비했습니다. 다양한 유형의 문제로 구성했으며, 객체지향 프로그래밍의 핵심 개념을 테스트할 수 있도록 했습니다.</p>
<h2 id="객관식-문제-각-5점">객관식 문제 (각 5점)</h2>
<ol>
<li>파이썬에서 객체의 인스턴스 변수를 클래스 외부로부터 보호하기 위해 사용하는 명명법은?<ul>
<li>a) _variable</li>
<li>b) __variable</li>
<li>c) variable_</li>
<li>d) <em>variable</em></li>
</ul>
</li>
<li>파이썬 클래스의 생성자 메소드 이름은?<ul>
<li>a) <strong>construct</strong></li>
<li>b) <strong>new</strong></li>
<li>c) <strong>init</strong></li>
<li>d) <strong>create</strong></li>
</ul>
</li>
<li>객체의 현재 상태를 문자열로 요약해주는 메소드는?<ul>
<li>a) <strong>str</strong></li>
<li>b) <strong>print</strong></li>
<li>c) toString()</li>
<li>d) <strong>repr</strong></li>
</ul>
</li>
<li>파이썬에서 클래스 외부에서 __name과 같은 비공개(private) 변수에 접근하는 올바른 방법은?<ul>
<li>a) object.__name</li>
<li>b) object._name</li>
<li>c) object._ClassName__name</li>
<li>d) object.getName()</li>
</ul>
</li>
<li>클래스 내부에서 인스턴스 변수를 참조할 때 사용하는 키워드는?<ul>
<li>a) this</li>
<li>b) self</li>
<li>c) instance</li>
<li>d) me</li>
</ul>
</li>
</ol>
<h2 id="단답형-문제-각-5점">단답형 문제 (각 5점)</h2>
<ol>
<li>객체지향 프로그래밍에서 인스턴스 변수에 대한 접근을 제어하는 메소드 중, 값을 반환하는 메소드를 무엇이라고 하는가?</li>
<li>객체지향 프로그래밍에서 인스턴스 변수에 대한 접근을 제어하는 메소드 중, 값을 설정하는 메소드를 무엇이라고 하는가?</li>
<li>파이썬에서 클래스의 인스턴스를 생성할 때 자동으로 호출되는 메소드는?</li>
<li>파이썬에서 비공개(private) 인스턴스 변수를 정의할 때 변수명 앞에 붙이는 기호는?</li>
<li>객체의 상태를 보호하고 외부에서 직접 접근하지 못하게 하는 객체지향 개념을 무엇이라고 하는가?</li>
</ol>
<h2 id="코드-분석-문제-각-10점">코드 분석 문제 (각 10점)</h2>
<ol>
<li>다음 코드의 실행 결과를 예측하시오.</li>
</ol>
<pre><code class="language-python">
python
class Student:
    def __init__(self, name=None, age=0):
        self.__name = name
        self.__age = age

    def getName(self):
        return self.__name

    def getAge(self):
        return self.__age

    def setName(self, name):
        self.__name = name

    def setAge(self, age):
        self.__age = age

obj = Student(&quot;Kim&quot;, 20)
print(obj.getName())
obj.setAge(21)
print(obj.getAge())
</code></pre>
<ol>
<li>다음 코드의 실행 결과를 예측하시오.</li>
</ol>
<pre><code class="language-python">
python
class Box:
    def __init__(self, length=0, width=0, height=0):
        self.__length = length
        self.__width = width
        self.__height = height

    def getVolume(self):
        return self.__length * self.__width * self.__height

    def __str__(self):
        return &#39;(%d, %d, %d)&#39; % (self.__length, self.__width, self.__height)

box = Box(5, 3, 2)
print(box)
print(&quot;부피:&quot;, box.getVolume())
</code></pre>
<ol>
<li>다음 코드의 오류를 찾고 수정하시오.</li>
</ol>
<pre><code class="language-python">
python
class Circle:
    def __init__(self, radius=1.0):
        self.__radius = radius

    def calcArea(self):
        area = 3.14 * self.__radius * self.__radius
        return area

c = Circle(5)
print(&quot;반지름:&quot;, c.__radius)
print(&quot;원의 넓이:&quot;, c.calcArea())
</code></pre>
<h2 id="코드-작성-문제-각-15점">코드 작성 문제 (각 15점)</h2>
<ol>
<li>직원(Employee) 클래스를 정의하시오. 이 클래스는 다음을 포함해야 합니다:<ul>
<li>이름(name), 직위(position), 급여(salary)를 인스턴스 변수로 가짐</li>
<li>인스턴스 변수는 모두 비공개로 설정</li>
<li>각 변수에 대한 접근자와 설정자 메소드 구현</li>
<li><strong>str</strong> 메소드를 구현하여 직원 정보를 문자열로 반환</li>
<li>급여를 인상하는 raiseSalary(percent) 메소드 구현 (percent는 인상 비율)</li>
</ul>
</li>
<li>주식(Stock) 클래스를 정의하시오. 이 클래스는 다음을 포함해야 합니다:<ul>
<li>종목명(symbol), 현재가(price), 보유수량(shares)을 인스턴스 변수로 가짐</li>
<li>인스턴스 변수는 모두 비공개로 설정</li>
<li>각 변수에 대한 접근자와 설정자 메소드 구현</li>
<li>총 가치를 계산하는 getTotalValue() 메소드 구현</li>
<li>주식을 구매하는 buy(amount) 메소드와 판매하는 sell(amount) 메소드 구현</li>
</ul>
</li>
<li>도서관 도서(LibraryBook) 클래스를 정의하시오. 이 클래스는 다음을 포함해야 합니다:<ul>
<li>제목(title), 저자(author), 대출상태(borrowed) 인스턴스 변수</li>
<li>인스턴스 변수는 모두 비공개로 설정</li>
<li>각 변수에 대한 접근자와 설정자 메소드 구현</li>
<li>도서를 대출하는 borrowBook() 메소드와 반납하는 returnBook() 메소드 구현</li>
<li><strong>str</strong> 메소드를 구현하여 도서 정보와 대출 상태를 문자열로 반환</li>
</ul>
</li>
</ol>
<h2 id="응용-문제-20점">응용 문제 (20점)</h2>
<ol>
<li>은행 시스템을 구현하기 위한 클래스를 설계하시오. 다음 요구사항을 만족해야 합니다:<ul>
<li>계좌(Account) 클래스는 계좌번호(accountNumber), 소유자명(ownerName), 잔액(balance)을 인스턴스 변수로 가짐</li>
<li>모든 인스턴스 변수는 비공개로 설정하고 적절한 접근자와 설정자 메소드 구현</li>
<li>입금(deposit), 출금(withdraw) 메소드 구현</li>
<li>출금 시 잔액이 부족하면 오류 메시지 출력</li>
<li><strong>str</strong> 메소드를 구현하여 계좌 정보를 문자열로 반환</li>
<li>계좌 클래스를 활용하여 입금, 출금, 계좌 정보 조회 기능을 테스트하는 코드 작성</li>
</ul>
</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter11. 틱택토, 객체지향프로그래밍]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter11.-%ED%8B%B1%ED%83%9D%ED%86%A0-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A5%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D</link>
            <guid>https://velog.io/@lullaby_/PythonChapter11.-%ED%8B%B1%ED%83%9D%ED%86%A0-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A5%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D</guid>
            <pubDate>Wed, 01 Oct 2025 01:27:35 GMT</pubDate>
            <description><![CDATA[<h2 id="1-tic-tac-toe-게임-프로그래밍">1. Tic-Tac-Toe 게임 프로그래밍</h2>
<h3 id="핵심-개념">핵심 개념</h3>
<ul>
<li>2차원 리스트를 활용한 게임 보드 표현</li>
<li>반복문과 조건문을 활용한 게임 로직 구현</li>
<li>랜덤 함수를 활용한 컴퓨터 플레이어 구현</li>
<li>승리 조건 확인 로직</li>
</ul>
<h3 id="주요-코드-구조">주요 코드 구조</h3>
<pre><code class="language-python">
python
# 게임 초기화
me = input(&quot;Tic-Tac_Toe게임입니다. 원하는 기호를 O, X 중에서 선택하시오 : &quot;)
if me == &quot;X&quot;:
    com = &quot;O&quot;
else:
    com = &quot;X&quot;
board = [[&#39; &#39; for x in range(5)] for y in range(5)]# 5x5 게임 보드 생성
result = &quot;&quot;
import random

# 게임 루프
while True:
# 현재 보드 상태 출력
    for r in range(5):
        print(&quot; &quot;+board[r][0]+&quot;| &quot;+board[r][1]+&quot;| &quot;+board[r][2]+&quot;| &quot;+board[r][3]+&quot;| &quot;+board[r][4])
        if (r!=4):
            print(&quot;---|---|---|---|---&quot;)

# 게임 종료 확인
    if result == &quot;win_me&quot;:
        print(&quot;당신이 컴퓨터를 이겼습니다.&quot;)
        break
    elif result == &quot;win_com&quot;:
        print(&quot;컴퓨터가 당신을 이겼습니다.&quot;)
        break

# 사용자 입력 받기
    x = int(input(&quot;(0 ~ 4)사이의 x좌표를 입력하시오:&quot;))
    y = int(input(&quot;(0 ~ 4)사이의 y좌표를 입력하시오:&quot;))

# 입력 위치 확인
    if board[x][y] != &#39; &#39;:
        print(&quot;잘못된 위치입니다.&quot;)
        continue
    else:
        board[x][y] = me

# 컴퓨터 차례
    while True:
        a = random.randrange(0, 5)# 0 이상 5 미만의 랜덤 숫자
        b = random.randrange(0, 5)# 0 이상 5 미만의 랜덤 숫자
        if board[a][b] == &#39; &#39;:
            board[a][b] = com
            break

# 승리 조건 확인 (수직, 수평, 대각선)# 수직 패턴 확인
    ver0 = []
    ver1 = []
    ver2 = []
    ver3 = []
    ver4 = []
    for i in range(5):
        ver0.append(board[i][0])
    for i in range(5):
        ver1.append(board[i][1])
    for i in range(5):
        ver2.append(board[i][2])
    for i in range(5):
        ver3.append(board[i][3])
    for i in range(5):
        ver4.append(board[i][4])

# 수평 패턴 확인
    hori0 = []
    hori1 = []
    hori2 = []
    hori3 = []
    hori4 = []
    for i in range(5):
        hori0.append(board[0][i])
    for i in range(5):
        hori1.append(board[1][i])
    for i in range(5):
        hori2.append(board[2][i])
    for i in range(5):
        hori3.append(board[3][i])
    for i in range(5):
        hori4.append(board[4][i])

# 대각선 패턴 확인
    dia0 = []
    dia1 = []
    for i in range(5):
        dia0.append(board[i][i])
    for i in range(5):
        dia1.append(board[i][4-i])

# 승리 조건 검사
    w_m = [me, me, me, me, me]# 사용자 승리 패턴
    w_c = [com, com, com, com, com]# 컴퓨터 승리 패턴

    if ((ver0 == w_m) or (ver1 == w_m) or (ver2 == w_m) or (ver3 == w_m) or (ver4 == w_m) or
        (hori0 == w_m) or (hori1 == w_m) or (hori2 == w_m) or (hori3 == w_m) or (hori4 == w_m) or
        (dia0 == w_m) or (dia1 == w_m)):
        result = &quot;win_me&quot;
    elif ((ver0 == w_c) or (ver1 == w_c) or (ver2 == w_c) or (ver3 == w_c) or (ver4 == w_c) or
          (hori0 == w_c) or (hori1 == w_c) or (hori2 == w_c) or (hori3 == w_c) or (hori4 == w_c) or
          (dia0 == w_c) or (dia1 == w_c)):
        result = &quot;win_com&quot;
</code></pre>
<h2 id="2-객체-지향-프로그래밍">2. 객체 지향 프로그래밍</h2>
<h3 id="핵심-개념-1">핵심 개념</h3>
<ul>
<li>객체(Object): <strong>상태</strong>(인스턴스 변수)와 <strong>동작</strong>(메소드)을 가진 요소</li>
<li>클래스(Class): 객체의 설계도</li>
<li>인스턴스(Instance): 클래스로부터 만들어진 객체</li>
<li><strong>인스턴스 변수: 객체의 상태를 나타내는 변수(<code>self.변수명</code>)</strong></li>
<li>메소드(Method): 객체의 동작을 정의하는 함수</li>
<li>캡슐화(Encapsulation): 데이터와 알고리즘을 하나로 묶는 것</li>
</ul>
<h3 id="클래스-구조">클래스 구조</h3>
<pre><code class="language-python">class 클래스이름:
    def 메소드1(self, 매개변수들):
# 메소드 내용
        self.인스턴스변수 = 값

    def 메소드2(self, 매개변수들):
# 메소드 내용
</code></pre>
<h3 id="객체-생성-및-사용">객체 생성 및 사용</h3>
<pre><code class="language-python">객체변수 = 클래스이름()# 객체 생성
객체변수.메소드()# 메소드 호출
</code></pre>
<h3 id="counter-클래스-예제">Counter 클래스 예제</h3>
<pre><code class="language-python">
python
class Counter:
    def reset(self):
        self.count = 0

    def increment(self):
        self.count += 1

    def get(self):
        return self.count

# 사용 예시
a = Counter()
a.reset()
a.increment()
print(&quot;카운터 a의 값은&quot;, a.get())# 카운터 a의 값은 1
print(&quot;카운터 a의 값은&quot;, a.count)# 카운터 a의 값은 1# 두 개의 독립적인 객체 생성
b = Counter()
a.reset()
b.reset()
a.increment()
print(&quot;카운터 a의 값은&quot;, a.get())# 카운터 a의 값은 1
print(&quot;카운터 b의 값은&quot;, b.get())# 카운터 b의 값은 0
</code></pre>
<h3 id="객체-지향-프로그래밍의-장점">객체 지향 프로그래밍의 장점</h3>
<ol>
<li>생산성 향상: 잘 설계된 클래스 재사용</li>
<li>자연적인 모델링: 일상 개념을 프로그래밍으로 표현</li>
<li>유지보수 용이성: 수정 및 기능 추가가 쉬움</li>
<li>캡슐화: 데이터와 함수를 하나로 묶어 관리</li>
</ol>
<h2 id="기말고사-예상-문제">기말고사 예상 문제</h2>
<h2 id="객관식-문제">객관식 문제</h2>
<ol>
<li>파이썬에서 객체는 다음 중 무엇으로 구성되는가?
a) 함수와 변수
b) 인스턴스 변수와 메소드
c) 클래스와 상속
d) 속성과 프로퍼티</li>
<li>다음 중 객체지향 프로그래밍의 장점이 아닌 것은?
a) 생산성 향상
b) 자연적인 모델링
c) 유지보수의 용이성
d) 메모리 사용량 감소</li>
<li>파이썬에서 클래스의 메소드를 정의할 때 첫 번째 매개변수로 주로 사용되는 것은?
a) cls
b) self
c) this
d) method</li>
<li>객체지향 프로그래밍에서 데이터와 알고리즘을 하나로 묶고 공용 인터페이스만 제공하고 구현 세부 사항을 감추는 것을 무엇이라고 하는가?
a) 추상화
b) 다형성
c) 캡슐화
d) 상속</li>
<li>Tic-Tac-Toe 게임 프로그래밍에서 게임판(board)을 초기화하는 코드로 올바른 것은?
a) board = [&#39; &#39; for x in range(5)]
b) board = [[&#39; &#39; for x in range(5)]]
c) board = [[&#39; &#39; for x in range(5)] for y in range(5)]
d) board = [for x in range(5) for y in range(5)]</li>
</ol>
<h2 id="단답형-문제">단답형 문제</h2>
<ol>
<li>객체지향 프로그래밍에서 클래스로부터 만들어지는 각각의 객체를 무엇이라고 하는가?</li>
<li>파이썬에서 인스턴스 변수를 생성하려면 메소드 안에서 어떤 키워드를 변수 앞에 붙여야 하는가?</li>
<li>Tic-Tac-Toe 게임에서 컴퓨터가 랜덤한 위치에 표시를 하기 위해 사용하는 파이썬 모듈은 무엇인가?</li>
<li>객체지향 프로그래밍에서 기존 클래스의 기능을 확장하여 새로운 클래스를 만드는 기법을 무엇이라고 하는가?</li>
<li>Tic-Tac-Toe 게임에서 승리 조건을 확인하기 위해 사용되는 패턴의 세 가지 종류는 무엇인가?</li>
</ol>
<h2 id="코드-분석-문제">코드 분석 문제</h2>
<ol>
<li>다음 코드의 실행 결과는 무엇인가?</li>
</ol>
<pre><code class="language-python">
python
class Counter:
    def reset(self):
        self.count = 0
    def increment(self):
        self.count += 1
    def get(self):
        return self.count

a = Counter()
a.reset()
a.increment()
a.increment()
print(&quot;카운터 a의 값은&quot;, a.get())
</code></pre>
<ol>
<li>다음 Tic-Tac-Toe 게임 코드에서 빈칸에 들어갈 올바른 코드는?</li>
</ol>
<pre><code class="language-python">
python
# 대각선 패턴 win append
dia0 = []
dia1 = []
for i in range(5):
    dia0.append(board[i][i])
for i in range(5):
    _________________# 이 부분에 들어갈 코드는?
</code></pre>
<h2 id="코드-작성-문제">코드 작성 문제</h2>
<ol>
<li>아래 Counter 클래스를 완성하되, 다음 요구사항을 만족시키시오:<ul>
<li>reset() 메소드: count를 0으로 초기화</li>
<li>increment() 메소드: count를 1 증가</li>
<li>decrement() 메소드: count를 1 감소 (단, 0보다 작아지지 않도록)</li>
<li>get() 메소드: 현재 count 값 반환</li>
</ul>
</li>
</ol>
<pre><code class="language-python">
python
class Counter:
# 코드를 작성하시오
</code></pre>
<ol>
<li>Tic-Tac-Toe 게임에서 사용자의 입력을 받아 보드에 표시하는 코드를 작성하시오. 이미 표시된 위치에는 중복해서 표시할 수 없어야 합니다.</li>
<li>객체지향 프로그래밍 개념을 이용하여 간단한 TV 클래스를 설계하고 구현하시오. TV 클래스는 다음 속성과 메소드를 가져야 합니다:<ul>
<li>속성: 채널번호, 볼륨, 전원상태</li>
<li>메소드: 켜기, 끄기, 채널 변경하기, 볼륨 변경하기</li>
</ul>
</li>
</ol>
<h2 id="서술형-문제">서술형 문제</h2>
<ol>
<li>객체지향 프로그래밍의 주요 특징과 장점을 세 가지 이상 설명하시오.</li>
<li>Tic-Tac-Toe 게임에서 승리 조건을 확인하는 방법에 대해 설명하고, 코드로 구현하는 방법을 서술하시오.</li>
<li>파이썬에서 &quot;모든 것이 객체&quot;라는 말이 의미하는 바를 설명하고, 예시를 들어 서술하시오.</li>
</ol>
<h2 id="종합-문제">종합 문제</h2>
<ol>
<li>객체지향 방법론을 활용하여 Tic-Tac-Toe 게임을 클래스로 구현하는 방법을 설명하고, 주요 메소드와 속성을 설계하시오.</li>
<li>다음과 같은 Counter 클래스를 상속받아 새로운 기능을 추가한 AdvancedCounter 클래스를 작성하시오. AdvancedCounter 클래스는 기존 기능에 추가로 reset_to(n) 메소드로 특정 값으로 초기화 기능과 현재까지의 increment 호출 횟수를 저장하는 기능을 가져야 합니다.</li>
</ol>
<pre><code class="language-python">
python
class Counter:
    def reset(self):
        self.count = 0
    def increment(self):
        self.count += 1
    def get(self):
        return self.count

class AdvancedCounter(Counter):
# 코드를 작성하시오
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter10. 정규표현식, 딕셔너리+, 튜플]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter10.-%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D-%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC-%ED%8A%9C%ED%94%8C-47yexrn1</link>
            <guid>https://velog.io/@lullaby_/PythonChapter10.-%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D-%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC-%ED%8A%9C%ED%94%8C-47yexrn1</guid>
            <pubDate>Wed, 01 Oct 2025 01:25:53 GMT</pubDate>
            <description><![CDATA[<h2 id="1-정규표현식regular-expressions-핵심-개념시험범위-미포함">1. 정규표현식(Regular Expressions) 핵심 개념~~시험범위 미포함</h2>
<h3 id="11-정규표현식-기본-개념">1.1 정규표현식 기본 개념</h3>
<ul>
<li><strong>정의</strong>: 특정한 규칙을 가진 문자열의 집합을 표현하는 형식 언어</li>
<li><strong>용도</strong>: 문자열 검색, 치환, 필터링 등에 사용</li>
<li><strong>파이썬 모듈</strong>: <code>re</code> 모듈 사용 (파이썬 기본 라이브러리)</li>
</ul>
<h3 id="12-메타-문자">1.2 메타 문자</h3>
<p>다음 문자들은 특별한 의미를 가진 메타 문자입니다:</p>
<pre><code>. ^ $ * + ? { } [ ] \ | ( )
</code></pre><h3 id="주요-메타-문자-의미">주요 메타 문자 의미:</h3>
<ul>
<li><input disabled="" type="checkbox"> <strong>[ ] - 문자 클래스: 괄호 안의 문자 중 하나와 매치</strong><ul>
<li><code>[abc]</code>: a, b, c 중 하나와 매치</li>
<li><code>[a-z]</code>: a부터 z까지 소문자 알파벳과 매치</li>
<li><code>[0-9]</code>: 숫자와 매치</li>
<li><code>[^0-9]</code>: 숫자가 아닌 문자와 매치 (^ 은 부정)</li>
</ul>
</li>
</ul>
<ol>
<li><strong>단축 표현</strong>:<ul>
<li><code>\d</code>: 숫자와 매치 (= <code>[0-9]</code>)</li>
<li><code>\D</code>: 숫자가 아닌 것과 매치 (= <code>[^0-9]</code>)</li>
<li><code>\s</code>: 공백 문자와 매치 (= <code>[ \t\n\r\f\v]</code>)</li>
<li><code>\S</code>: 공백이 아닌 문자와 매치</li>
<li><code>\w</code>: 문자+숫자와 매치 (= <code>[a-zA-Z0-9_]</code>)</li>
<li><code>\W</code>: 문자+숫자가 아닌 것과 매치</li>
</ul>
</li>
<li><strong>.</strong> (Dot): 줄바꿈(<code>\n</code>)을 제외한 모든 문자와 매치<ul>
<li><code>a.b</code>: a와 b 사이에 어떤 문자든 한 개 있는 패턴</li>
</ul>
</li>
<li><strong>반복 관련 메타 문자</strong>:<ul>
<li>: 0번 이상 반복 (= <code>{0,}</code>)</li>
<li><code>+</code>: 1번 이상 반복 (= <code>{1,}</code>)</li>
<li><code>?</code>: 0번 또는 1번 (= <code>{0,1}</code>)</li>
<li><code>{m}</code>: 정확히 m번 반복</li>
<li><code>{m,n}</code>: m번 이상 n번 이하 반복</li>
</ul>
</li>
</ol>
<h3 id="13-정규표현식-사용-방법">1.3 정규표현식 사용 방법</h3>
<ol>
<li><p><strong>re.compile()</strong>: 정규표현식 패턴 컴파일</p>
<pre><code class="language-python"> import re
 p = re.compile(&#39;[a-z]+&#39;)  # 소문자 알파벳 1개 이상
</code></pre>
</li>
<li><p><strong>주요 메서드</strong>:</p>
<ul>
<li><code>match()</code>: 문자열의 처음부터 매치 검사</li>
<li><code>search()</code>: 문자열 <strong>전체에서</strong> 첫 번째 매치 검사</li>
<li><code>findall()</code>: <strong>모든 매치를 리스트로 반환</strong></li>
<li><code>finditer()</code>: <strong>모든 매치를 반복 가능한 객체로 반환</strong></li>
</ul>
</li>
<li><p><strong>매치 객체 메서드</strong>:</p>
<ul>
<li><code>group()</code>: 매치된 문자열 반환</li>
<li><code>start()</code>: 매치 시작 위치 반환</li>
<li><code>end()</code>: 매치 끝 위치 반환</li>
<li><code>span()</code>: (시작, 끝) 튜플 반환</li>
</ul>
</li>
</ol>
<h2 id="2-딕셔너리dictionary와-튜플tuple">2. 딕셔너리(Dictionary)와 튜플(Tuple)</h2>
<h3 id="21-딕셔너리dictionary">2.1 딕셔너리(Dictionary)</h3>
<ul>
<li><strong>정의</strong>: 키(key)와 값(value)의 쌍으로 이루어진 자료구조</li>
<li><strong>특징</strong>:<ul>
<li>키는 중복될 수 없음</li>
<li>키를 통해 값에 빠르게 접근 가능</li>
<li>순서가 없음 (Python 3.7부터는 삽입 순서 유지)</li>
</ul>
</li>
</ul>
<h3 id="딕셔너리-활용-예">딕셔너리 활용 예:</h3>
<pre><code class="language-python"># 단어 카운팅
word_count = {}
for word in words:
    if word not in word_count:
        word_count[word] = 1
    else:
        word_count[word] += 1
</code></pre>
<h3 id="22-튜플tuple">2.2 튜플(Tuple)</h3>
<ul>
<li><strong>정의</strong>: <strong>순서가 있는 변경 불가능한(immutable) 자료구조</strong></li>
<li><strong>특징</strong>:<ul>
<li><strong>한번 생성하면 변경할 수 없음</strong></li>
<li>인덱싱, 슬라이싱 가능</li>
<li>여러 값을 패킹/언패킹하여 동시에 다룰 수 있음</li>
</ul>
</li>
</ul>
<h3 id="튜플-활용-예">튜플 활용 예:</h3>
<pre><code class="language-python"># 함수에서 여러 값 반환
def calculate_circle(r):
    area = math.pi * r * r
    circumference = 2 * math.pi * r
    return (area, circumference)

# 언패킹
(a, c) = calculate_circle(10)
</code></pre>
<h1 id="예상문제-및-풀이">예상문제 및 풀이</h1>
<h2 id="1-정규표현식-regular-expressions-문제">1. 정규표현식 (Regular Expressions) 문제</h2>
<h3 id="문제-1-기본-개념">문제 1: 기본 개념</h3>
<p>다음 정규표현식이 매치하는 패턴을 설명하세요.</p>
<ol>
<li><code>[a-zA-Z0-9]+</code></li>
<li><code>\d{3}-\d{3}-\d{4}</code></li>
<li><code>[^0-9]</code></li>
<li><code>a.b</code></li>
<li><code>ca{2,5}t</code></li>
</ol>
<p><strong>답안:</strong></p>
<ol>
<li>알파벳 대소문자와 숫자가 1개 이상 반복되는 패턴</li>
<li>000-000-0000 형식의 전화번호 패턴</li>
<li>숫자가 아닌 모든 문자 중 1개</li>
<li>a와 b 사이에 어떤 문자든 한 개 있는 패턴(예: aab, a0b)</li>
<li>c 다음에 a가 2~5회 반복된 후 t가 오는 패턴(caat, caaat, caaaat, caaaaat)</li>
</ol>
<h3 id="문제-2-re-모듈-메서드">문제 2: re 모듈 메서드</h3>
<p>다음 코드의 실행 결과를 예측하세요.</p>
<pre><code class="language-python">import re

text = &quot;Python is fun. python is easy. PYTHON is powerful.&quot;
pattern = re.compile(&#39;[Pp]ython&#39;)

# (a) match 메서드 결과
result1 = pattern.match(text)
print(result1)

# (b) search 메서드 결과
result2 = pattern.search(text)
print(result2)

# (c) findall 메서드 결과
result3 = pattern.findall(text)
print(result3)
</code></pre>
<p><strong>답안:</strong></p>
<pre><code># (a) match 메서드 결과
&lt;re.Match object; span=(0, 6), match=&#39;Python&#39;&gt;

# (b) search 메서드 결과
&lt;re.Match object; span=(0, 6), match=&#39;Python&#39;&gt;

# (c) findall 메서드 결과
[&#39;Python&#39;, &#39;python&#39;]
</code></pre><h3 id="문제-3-이메일-주소-검증">문제 3: 이메일 주소 검증</h3>
<p>다음 이메일 주소가 올바른 형식인지 검증하는 정규표현식 패턴을 작성하세요.
이메일 형식: 사용자이름@도메인.최상위도메인</p>
<pre><code class="language-python">import re

def validate_email(email):
    pattern = re.compile(r&#39;^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$&#39;)
    if pattern.match(email):
        return True
    else:
        return False

# 테스트
emails = [&quot;user@example.com&quot;, &quot;invalid-email&quot;, &quot;another.user@sub.domain.co.kr&quot;, &quot;no@domain&quot;]
for email in emails:
    print(f&quot;{email}: {validate_email(email)}&quot;)
</code></pre>
<p><strong>실행 결과:</strong></p>
<pre><code>user@example.com: True
invalid-email: False
another.user@sub.domain.co.kr: True
no@domain: False
</code></pre><h3 id="문제-4-로그-파일-분석">문제 4: 로그 파일 분석</h3>
<p>다음 로그 파일에서 에러 코드가 포함된 라인만 추출하는 프로그램을 작성하세요.
에러 코드 형식: ERROR-숫자4자리</p>
<pre><code class="language-python">import re

def extract_errors(log_file):
    error_pattern = re.compile(r&#39;ERROR-\d{4}&#39;)
    errors = []

    with open(log_file, &#39;r&#39;) as f:
        for line in f:
            if error_pattern.search(line):
                errors.append(line.strip())

    return errors

# 예시 로그 파일 생성 (실제 시험에서는 주어질 수 있음)
sample_log = &quot;&quot;&quot;
2023-05-14 12:30:45 INFO: System started
2023-05-14 12:35:22 ERROR-1033: Invalid argument
2023-05-14 12:40:11 WARNING: Low memory
2023-05-14 12:45:30 ERROR-2045: Connection failed
2023-05-14 12:50:15 INFO: Process completed
&quot;&quot;&quot;

with open(&#39;sample.log&#39;, &#39;w&#39;) as f:
    f.write(sample_log)

# 에러 라인 추출
errors = extract_errors(&#39;sample.log&#39;)
for error in errors:
    print(error)
</code></pre>
<p><strong>실행 결과:</strong></p>
<pre><code>2023-05-14 12:35:22 ERROR-1033: Invalid argument
2023-05-14 12:45:30 ERROR-2045: Connection failed
</code></pre><h2 id="2-딕셔너리와-튜플-문제">2. 딕셔너리와 튜플 문제</h2>
<h3 id="문제-5-단어-빈도수-계산">문제 5: 단어 빈도수 계산</h3>
<p>텍스트 파일에서 각 단어의 빈도수를 계산하여 출력하는 프로그램을 작성하세요.</p>
<pre><code class="language-python">def count_words(filename):
    word_count = {}

    try:
        with open(filename, &#39;r&#39;) as file:
            for line in file:
                words = line.strip().split()
                for word in words:
                    if word not in word_count:
                        word_count[word] = 1
                    else:
                        word_count[word] += 1

        return word_count
    except FileNotFoundError:
        print(f&quot;파일 &#39;{filename}&#39;을 찾을 수 없습니다.&quot;)
        return {}

# 테스트용 파일 생성
sample_text = &quot;&quot;&quot;
Well begun is half done.
Good morning
Birds of a feather flock together.
Well begun is half done.
Birds of a feather flock together.
Well begun is half done.
&quot;&quot;&quot;

with open(&#39;word_count.txt&#39;, &#39;w&#39;) as f:
    f.write(sample_text)

# 단어 빈도수 계산
result = count_words(&#39;word_count.txt&#39;)
print(result)
</code></pre>
<p><strong>실행 결과:</strong></p>
<pre><code>{&#39;Well&#39;: 3, &#39;begun&#39;: 3, &#39;is&#39;: 3, &#39;half&#39;: 3, &#39;done.&#39;: 3, &#39;Good&#39;: 1, &#39;morning&#39;: 1, &#39;Birds&#39;: 2, &#39;of&#39;: 2, &#39;a&#39;: 2, &#39;feather&#39;: 2, &#39;flock&#39;: 2, &#39;together.&#39;: 2}
</code></pre><h3 id="문제-6-축약어-변환기">문제 6: 축약어 변환기</h3>
<p>축약어를 원래 단어로 변환하는 프로그램을 작성하세요.</p>
<pre><code class="language-python">def expand_abbreviations(message):
    abbreviations = {
        &quot;B4&quot;: &quot;Before&quot;,
        &quot;TX&quot;: &quot;Thanks&quot;,
        &quot;BBL&quot;: &quot;Be Back Later&quot;,
        &quot;BCNU&quot;: &quot;Be Seeing You&quot;,
        &quot;HAND&quot;: &quot;Have A Nice Day&quot;
    }

    words = message.split()
    result = &quot;&quot;

    for word in words:
        if word in abbreviations:
            result += abbreviations[word] + &quot; &quot;
        else:
            result += word + &quot; &quot;

    return result.strip()

# 테스트
message = &quot;TX Mr. Park! HAND&quot;
expanded = expand_abbreviations(message)
print(f&quot;입력: {message}&quot;)
print(f&quot;출력: {expanded}&quot;)
</code></pre>
<p><strong>실행 결과:</strong></p>
<pre><code>입력: TX Mr. Park! HAND
출력: Thanks Mr. Park! Have A Nice Day
</code></pre><h3 id="문제-7-원의-계산-함수">문제 7: 원의 계산 함수</h3>
<p>반지름을 입력받아 원의 넓이와 둘레를 계산하여 튜플로 반환하는 함수를 작성하세요.</p>
<pre><code class="language-python">import math

def calculate_circle(radius):
    area = math.pi * radius ** 2
    circumference = 2 * math.pi * radius
    return (area, circumference)

# 테스트
radius = 10
area, circumference = calculate_circle(radius)
print(f&quot;반지름이 {radius}인 원의:&quot;)
print(f&quot;- 넓이: {area}&quot;)
print(f&quot;- 둘레: {circumference}&quot;)
</code></pre>
<p><strong>실행 결과:</strong></p>
<pre><code>반지름이 10인 원의:
- 넓이: 314.1592653589793
- 둘레: 62.83185307179586
</code></pre><h3 id="문제-8-학생-정보-관리">문제 8: 학생 정보 관리</h3>
<p>학생 정보를 관리하는 프로그램을 작성하세요. 각 학생은 (이름, 나이, 전공) 튜플로 저장되며,
학생 목록을 딕셔너리로 관리하세요. 학번(키)으로 학생 정보를 조회하는 기능을 구현하세요.</p>
<pre><code class="language-python">def add_student(students, student_id, name, age, major):
    students[student_id] = (name, age, major)
    return students

def get_student(students, student_id):
    if student_id in students:
        return students[student_id]
    else:
        return None

def print_student_info(student):
    if student:
        name, age, major = student
        print(f&quot;이름: {name}&quot;)
        print(f&quot;나이: {age}&quot;)
        print(f&quot;전공: {major}&quot;)
    else:
        print(&quot;학생 정보가 없습니다.&quot;)

# 테스트
students = {}
students = add_student(students, &quot;2023001&quot;, &quot;홍길동&quot;, 20, &quot;컴퓨터과학&quot;)
students = add_student(students, &quot;2023002&quot;, &quot;김철수&quot;, 19, &quot;수학&quot;)
students = add_student(students, &quot;2023003&quot;, &quot;이영희&quot;, 21, &quot;물리학&quot;)

print(&quot;전체 학생 목록:&quot;)
for student_id, info in students.items():
    print(f&quot;{student_id}: {info[0]}&quot;)

print(&quot;\n학번 2023002 학생 정보:&quot;)
student = get_student(students, &quot;2023002&quot;)
print_student_info(student)

print(&quot;\n학번 2023004 학생 정보:&quot;)
student = get_student(students, &quot;2023004&quot;)
print_student_info(student)
</code></pre>
<p><strong>실행 결과:</strong></p>
<pre><code>전체 학생 목록:
2023001: 홍길동
2023002: 김철수
2023003: 이영희

학번 2023002 학생 정보:
이름: 김철수
나이: 19
전공: 수학

학번 2023004 학생 정보:
학생 정보가 없습니다.
</code></pre><h2 id="3-종합-문제">3. 종합 문제</h2>
<h3 id="문제-9-전화번호부-관리">문제 9: 전화번호부 관리</h3>
<p>정규표현식을 사용하여 전화번호 형식을 검증하고, 딕셔너리를 사용하여 전화번호부를 관리하는 프로그램을 작성하세요.</p>
<pre><code class="language-python">import re

class PhoneBook:
    def __init__(self):
        self.contacts = {}
        # 전화번호 형식: 000-000-0000 또는 (000) 000-0000
        self.phone_pattern = re.compile(r&#39;^\(\d{3}\)\s\d{3}-\d{4}$|^\d{3}-\d{3}-\d{4}$&#39;)

    def add_contact(self, name, phone_number):
        if not self.is_valid_phone(phone_number):
            print(f&quot;유효하지 않은 전화번호 형식입니다: {phone_number}&quot;)
            return False

        self.contacts[name] = phone_number
        print(f&quot;{name} 연락처가 추가되었습니다.&quot;)
        return True

    def is_valid_phone(self, phone_number):
        return bool(self.phone_pattern.match(phone_number))

    def find_contact(self, name):
        if name in self.contacts:
            return self.contacts[name]
        else:
            return None

    def list_contacts(self):
        if not self.contacts:
            print(&quot;전화번호부가 비어있습니다.&quot;)
        else:
            print(&quot;연락처 목록:&quot;)
            for name, phone in self.contacts.items():
                print(f&quot;{name}: {phone}&quot;)

# 테스트
phone_book = PhoneBook()
phone_book.add_contact(&quot;홍길동&quot;, &quot;010-123-4567&quot;)  # 잘못된 형식
phone_book.add_contact(&quot;홍길동&quot;, &quot;010-1234-5678&quot;)  # 잘못된 형식
phone_book.add_contact(&quot;홍길동&quot;, &quot;010-123-4567&quot;)  # 잘못된 형식
phone_book.add_contact(&quot;홍길동&quot;, &quot;123-456-7890&quot;)  # 올바른 형식
phone_book.add_contact(&quot;김철수&quot;, &quot;(123) 456-7890&quot;)  # 올바른 형식
phone_book.add_contact(&quot;이영희&quot;, &quot;987-654-3210&quot;)  # 올바른 형식

print(&quot;\n홍길동의 연락처:&quot;, phone_book.find_contact(&quot;홍길동&quot;))
print(&quot;박지성의 연락처:&quot;, phone_book.find_contact(&quot;박지성&quot;))

print(&quot;\n전체 연락처 목록:&quot;)
phone_book.list_contacts()
</code></pre>
<p><strong>실행 결과:</strong></p>
<pre><code>유효하지 않은 전화번호 형식입니다: 010-123-4567
유효하지 않은 전화번호 형식입니다: 010-1234-5678
유효하지 않은 전화번호 형식입니다: 010-123-4567
홍길동 연락처가 추가되었습니다.
김철수 연락처가 추가되었습니다.
이영희 연락처가 추가되었습니다.

홍길동의 연락처: 123-456-7890
박지성의 연락처: None

전체 연락처 목록:
연락처 목록:
홍길동: 123-456-7890
김철수: (123) 456-7890
이영희: 987-654-3210
</code></pre><h3 id="문제-10-이메일-주소-추출-및-통계">문제 10: 이메일 주소 추출 및 통계</h3>
<p>주어진 텍스트에서 모든 이메일 주소를 추출하고, 도메인별 이메일 개수를 계산하는 프로그램을 작성하세요.</p>
<pre><code class="language-python">import re

def extract_emails(text):
    email_pattern = re.compile(r&#39;[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}&#39;)
    return email_pattern.findall(text)

def count_domains(emails):
    domain_counts = {}

    for email in emails:
        # @ 이후의 도메인 부분 추출
        domain = email.split(&#39;@&#39;)[1]

        if domain not in domain_counts:
            domain_counts[domain] = 1
        else:
            domain_counts[domain] += 1

    return domain_counts

# 테스트용 텍스트
sample_text = &quot;&quot;&quot;
Contact us at support@example.com for help.
Send your resume to jobs@company.co.kr if you&#39;re interested.
For technical questions: tech@support.example.com or admin@example.com.
Marketing team: marketing@company.co.kr, sales@company.co.kr.
&quot;&quot;&quot;

# 이메일 추출
emails = extract_emails(sample_text)
print(&quot;추출된 이메일 주소:&quot;)
for email in emails:
    print(email)

# 도메인별 통계
domain_stats = count_domains(emails)
print(&quot;\n도메인별 이메일 개수:&quot;)
for domain, count in domain_stats.items():
    print(f&quot;{domain}: {count}개&quot;)
</code></pre>
<p><strong>실행 결과:</strong></p>
<pre><code>추출된 이메일 주소:
support@example.com
jobs@company.co.kr
tech@support.example.com
admin@example.com
marketing@company.co.kr
sales@company.co.kr

도메인별 이메일 개수:
example.com: 2개
company.co.kr: 3개
support.example.com: 1개
</code></pre>]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter09. 다차원 리스트, 딕셔너리]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter10.-%EB%8B%A4%EC%B0%A8%EC%9B%90-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC-yhtbnzar</link>
            <guid>https://velog.io/@lullaby_/PythonChapter10.-%EB%8B%A4%EC%B0%A8%EC%9B%90-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EB%94%95%EC%85%94%EB%84%88%EB%A6%AC-yhtbnzar</guid>
            <pubDate>Wed, 01 Oct 2025 01:23:41 GMT</pubDate>
            <description><![CDATA[<h2 id="1-다차원-리스트-2d-lists">1. 다차원 리스트 (2D Lists)</h2>
<h3 id="11-개념-정리">1.1 개념 정리</h3>
<p><strong>2차원 리스트란?</strong></p>
<ul>
<li>리스트 안에 리스트가 포함된 형태의 자료구조</li>
<li>행렬(matrix), 표(table) 등의 데이터를 표현할 때 사용</li>
<li>행(row)과 열(column)을 이용하여 데이터에 접근</li>
</ul>
<p><strong>2차원 리스트 생성 방법</strong></p>
<ol>
<li><strong>직접 정의</strong></li>
</ol>
<pre><code class="language-python">s = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15]
]
</code></pre>
<ol>
<li><strong>동적 생성 (반복문 활용)</strong></li>
</ol>
<pre><code class="language-python">rows = 3
cols = 5
s = []
for row in range(rows):
    s += [[0] * cols]  # 중요: [0] * cols는 0으로 채워진 cols 길이의 1차원 리스트
</code></pre>
<ol>
<li><strong>리스트 내포(List Comprehension) 활용</strong></li>
</ol>
<pre><code class="language-python">rows = 6
cols = 6
table = [[0] * cols for i in range(rows)]
</code></pre>
<h3 id="12-2차원-리스트-접근-방법">1.2 2차원 리스트 접근 방법</h3>
<p><strong>인덱싱을 통한 접근</strong></p>
<pre><code class="language-python">s = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15]
]
print(s[0])     # 첫 번째 행 전체: [1, 2, 3, 4, 5]
print(s[1][2])  # 두 번째 행, 세 번째 열: 8
</code></pre>
<p><strong>반복문을 이용한 2차원 리스트 순회</strong></p>
<pre><code class="language-python">rows = len(s)        # 행의 개수
cols = len(s[0])     # 열의 개수

for r in range(rows):
    for c in range(cols):
        print(s[r][c], end=&quot; &quot;)
    print()  # 한 행이 끝나면 줄바꿈
</code></pre>
<h3 id="13-다양한-형식의-데이터를-저장한-다차원-리스트">1.3 다양한 형식의 데이터를 저장한 다차원 리스트</h3>
<pre><code class="language-python">list = [[&quot;Seoul&quot;, 10], [&quot;Paris&quot;, 12], [&quot;London&quot;, 50]]
# 리스트 안에 문자열과 숫자를 함께 저장할 수 있음

# 문자열에 대한 인덱싱도 가능
print(list[0][0][0])  # &quot;Seoul&quot;의 첫 번째 글자: &#39;S&#39;
</code></pre>
<pre><code class="language-python"># 더 복잡한 다차원 리스트
list = [&quot;atom&quot;, [&quot;bold&quot;, [&quot;crew&quot;, [&quot;date&quot;, &quot;easy&quot;, 45]]]]
</code></pre>
<h2 id="2-딕셔너리-dictionary">2. 딕셔너리 (Dictionary)</h2>
<h3 id="21-개념-정리">2.1 개념 정리</h3>
<p><strong>딕셔너리란?</strong></p>
<ul>
<li>키(key)와 값(value)의 쌍으로 이루어진 자료구조</li>
<li>순서가 없고, 키를 통해 값에 접근</li>
<li><strong>키는 중복될 수 없고, 값은 중복될 수 있음</strong></li>
</ul>
<p><strong>딕셔너리 생성 방법</strong></p>
<ol>
<li><strong>중괄호를 이용한 직접 정의</strong></li>
</ol>
<pre><code class="language-python">contacts = {&#39;Kim&#39;: &#39;01012345678&#39;, &#39;Park&#39;: &#39;01012345679&#39;, &#39;Lee&#39;: &#39;01012345680&#39;}
</code></pre>
<ol>
<li><strong>dict() 함수 활용</strong></li>
</ol>
<pre><code class="language-python">dic = dict()
dic[&#39;kim&#39;] = 23
dic[20001] = 22  # 키는 문자열뿐만 아니라 정수형도 가능
</code></pre>
<h3 id="22-딕셔너리-조작-방법">2.2 딕셔너리 조작 방법</h3>
<p>get(key, default value) ⇒ key의 value를 리턴함(키가 없으면 디폴트 밸류 출력)</p>
<p><strong>데이터 검색</strong></p>
<pre><code class="language-python">contacts = {&#39;Kim&#39;: &#39;01012345678&#39;, &#39;Park&#39;: &#39;01012345679&#39;, &#39;Lee&#39;: &#39;01012345680&#39;}
print(contacts[&#39;Kim&#39;])                 # &#39;01012345678&#39; (키가 없으면 오류)
print(contacts.get(&#39;Kim&#39;))             # &#39;01012345678&#39;
print(contacts.get(&#39;Choi&#39;))            # None (키가 없어도 오류 없음)
print(contacts.get(&#39;Choi&#39;, &quot;없음&quot;))     # &#39;없음&#39; (키가 없을 때 기본값 설정)
</code></pre>
<p><strong>키 존재 여부 확인</strong></p>
<pre><code class="language-python">if &quot;Kim&quot; in contacts:
    print(&quot;키가 딕셔너리에 있음&quot;)
</code></pre>
<p><strong>데이터 추가/수정</strong></p>
<pre><code class="language-python">contacts[&#39;Choi&#39;] = &#39;01056781234&#39;  # 새 항목 추가
contacts[&#39;Kim&#39;] = &#39;01099998888&#39;   # 기존 항목 수정
</code></pre>
<p><strong>데이터 삭제</strong></p>
<pre><code class="language-python">phone = contacts.pop(&quot;Kim&quot;)  # &#39;Kim&#39; 항목을 삭제하고 값을 반환
</code></pre>
<h3 id="23-딕셔너리-순회-방법">2.3 딕셔너리 순회 방법</h3>
<p><strong>items() 메소드 활용(for i 도 가능): key, value 함께 출력함</strong></p>
<pre><code class="language-python">scores = {&#39;Korean&#39;: 80, &#39;Math&#39;: 90, &#39;English&#39;: 80}
for item in scores.items():
    print(item)  # (&#39;Korean&#39;, 80), (&#39;Math&#39;, 90), (&#39;English&#39;, 80)
</code></pre>
<p><strong>keys() 메소드 활용</strong></p>
<pre><code class="language-python">for key in scores.keys():
    print(key)  # &#39;Korean&#39;, &#39;Math&#39;, &#39;English&#39;
</code></pre>
<p><strong>values() 메소드 활용</strong></p>
<pre><code class="language-python">for value in scores.values():
    print(value)  # 80, 90, 80
</code></pre>
<h2 id="3-예상-문제-및-풀이">3. 예상 문제 및 풀이</h2>
<h3 id="문제-1-주사위-합계-테이블-만들기">문제 1: 주사위 합계 테이블 만들기</h3>
<p>두 개의 주사위를 굴렸을 때 나오는 숫자의 합을 6x6 크기의 2차원 리스트로 만드는 프로그램을 작성하세요.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python"># 6x6 크기의 2차원 리스트 생성
rows = 6
cols = 6
table = [[0] * cols for i in range(rows)]

# 각 칸에 주사위 합계 저장
for row in range(rows):
    for col in range(cols):
        table[row][col] = (row+1) + (col+1)

# 결과 출력
print(&quot; ||&quot;, end=&quot; &quot;)
for c in range(1, 7):
    print(&quot;%3d&quot; % (c), end=&quot; &quot;)
print()
print(&quot;=&quot;*40)

for r in range(6):
    print(r+1, &quot;|| &quot;, end=&quot;&quot;)
    for c in range(6):
        print(&quot;%3d&quot; % table[r][c], end=&quot; &quot;)
    print()
</code></pre>
<h3 id="문제-2-학생-성적-관리-프로그램">문제 2: 학생 성적 관리 프로그램</h3>
<p>학생의 이름과 성적을 딕셔너리로 관리하고, 평균 점수를 계산하는 프로그램을 작성하세요.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python"># 학생 성적 딕셔너리 생성
students = {
    &#39;김철수&#39;: {&#39;국어&#39;: 90, &#39;영어&#39;: 85, &#39;수학&#39;: 95},
    &#39;이영희&#39;: {&#39;국어&#39;: 78, &#39;영어&#39;: 88, &#39;수학&#39;: 92},
    &#39;박민수&#39;: {&#39;국어&#39;: 92, &#39;영어&#39;: 96, &#39;수학&#39;: 98}
}

# 각 학생의 평균 점수 계산 및 출력
for name, scores in students.items():
    total = sum(scores.values())
    average = total / len(scores)
    print(f&quot;{name}의 평균 점수: {average:.2f}&quot;)

# 과목별 평균 점수 계산
subjects = [&#39;국어&#39;, &#39;영어&#39;, &#39;수학&#39;]
for subject in subjects:
    total = 0
    for student in students.values():
        total += student[subject]
    average = total / len(students)
    print(f&quot;{subject} 과목 평균: {average:.2f}&quot;)
</code></pre>
<h3 id="문제-3-영한-사전-확장하기">문제 3: 영한 사전 확장하기</h3>
<p>영단어를 키로, 한글 설명을 값으로 하는 영한 사전을 만들고, 단어 추가, 삭제, 검색 기능을 구현하세요.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">def create_dictionary():
    english_dict = {
        &#39;one&#39;: &#39;하나&#39;,
        &#39;two&#39;: &#39;둘&#39;,
        &#39;three&#39;: &#39;셋&#39;,
        &#39;four&#39;: &#39;넷&#39;,
        &#39;five&#39;: &#39;다섯&#39;
    }
    return english_dict

def add_word(dictionary):
    eng = input(&quot;추가할 영단어를 입력하세요: &quot;)
    kor = input(&quot;단어의 뜻을 입력하세요: &quot;)
    dictionary[eng] = kor
    print(f&quot;&#39;{eng}: {kor}&#39;가 사전에 추가되었습니다.&quot;)

def delete_word(dictionary):
    eng = input(&quot;삭제할 영단어를 입력하세요: &quot;)
    if eng in dictionary:
        meaning = dictionary.pop(eng)
        print(f&quot;&#39;{eng}: {meaning}&#39;가 사전에서 삭제되었습니다.&quot;)
    else:
        print(f&quot;&#39;{eng}&#39;는 사전에 없습니다.&quot;)

def search_word(dictionary):
    eng = input(&quot;검색할 영단어를 입력하세요: &quot;)
    meaning = dictionary.get(eng, &quot;사전에 등록된 정보가 없음&quot;)
    print(f&quot;{eng}: {meaning}&quot;)

def print_all(dictionary):
    print(&quot;\n--- 영한 사전 전체 단어 ---&quot;)
    for eng, kor in dictionary.items():
        print(f&quot;{eng}: {kor}&quot;)

def main():
    dictionary = create_dictionary()

    while True:
        print(&quot;\n=== 영한 사전 프로그램 ===&quot;)
        print(&quot;1. 단어 검색&quot;)
        print(&quot;2. 단어 추가&quot;)
        print(&quot;3. 단어 삭제&quot;)
        print(&quot;4. 전체 단어 출력&quot;)
        print(&quot;5. 종료&quot;)

        choice = input(&quot;메뉴를 선택하세요: &quot;)

        if choice == &#39;1&#39;:
            search_word(dictionary)
        elif choice == &#39;2&#39;:
            add_word(dictionary)
        elif choice == &#39;3&#39;:
            delete_word(dictionary)
        elif choice == &#39;4&#39;:
            print_all(dictionary)
        elif choice == &#39;5&#39;:
            print(&quot;프로그램을 종료합니다.&quot;)
            break
        else:
            print(&quot;잘못된 메뉴입니다. 다시 선택해주세요.&quot;)

if __name__ == &quot;__main__&quot;:
    main()
</code></pre>
<h3 id="문제-4-도시별-인구-데이터-분석">문제 4: 도시별 인구 데이터 분석</h3>
<p>도시 이름과 인구수를 저장한 2차원 리스트를 만들고, 인구가 많은 순서대로 정렬하여 출력하는 프로그램을 작성하세요.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python"># 도시별 인구 데이터 (도시명, 인구수(만 명))
cities = [
    [&quot;Seoul&quot;, 980],
    [&quot;Busan&quot;, 340],
    [&quot;Incheon&quot;, 290],
    [&quot;Daegu&quot;, 240],
    [&quot;Daejeon&quot;, 150],
    [&quot;Gwangju&quot;, 145],
    [&quot;Ulsan&quot;, 115],
    [&quot;Suwon&quot;, 120]
]

# 인구수(두 번째 요소)를 기준으로 내림차순 정렬
cities.sort(key=lambda x: x[1], reverse=True)

# 결과 출력
print(&quot;=== 인구가 많은 순서 ===&quot;)
print(&quot;순위\t도시명\t인구수(만 명)&quot;)
for i, city in enumerate(cities, 1):
    print(f&quot;{i}\t{city[0]}\t{city[1]}&quot;)

# 인구수 평균 계산
total_population = sum(city[1] for city in cities)
average = total_population / len(cities)
print(f&quot;\n도시 평균 인구: {average:.2f}만 명&quot;)

# 평균보다 인구가 많은 도시 찾기
print(&quot;\n평균보다 인구가 많은 도시:&quot;)
for city in cities:
    if city[1] &gt; average:
        print(f&quot;{city[0]}: {city[1]}만 명&quot;)
</code></pre>
<h1 id="파이썬-기말고사-대비-실전-문제">파이썬 기말고사 대비 실전 문제</h1>
<h2 id="다차원-리스트-문제">다차원 리스트 문제</h2>
<h3 id="문제-1-행렬-덧셈">문제 1: 행렬 덧셈</h3>
<p>두 개의 2차원 리스트(행렬)를 입력받아 같은 위치의 원소를 더한 새로운 행렬을 반환하는 함수를 작성하세요.</p>
<pre><code>예시:
matrix_A = [[1, 2, 3], [4, 5, 6]]
matrix_B = [[7, 8, 9], [10, 11, 12]]

결과: [[8, 10, 12], [14, 16, 18]]
</code></pre><h3 id="문제-2-성적표-만들기">문제 2: 성적표 만들기</h3>
<p>학생들의 이름과 각 과목(국어, 영어, 수학) 점수를 입력받아 성적표를 출력하는 프로그램을 작성하세요. 각 학생별 총점과 평균, 그리고 과목별 평균도 함께 출력하세요.</p>
<pre><code>예시 입력:
students = [
    [&quot;김철수&quot;, 85, 90, 95],
    [&quot;이영희&quot;, 90, 85, 80],
    [&quot;박민수&quot;, 75, 80, 85]
]

예시 출력:
이름    국어  영어  수학  총점  평균
김철수  85   90   95   270   90.0
이영희  90   85   80   255   85.0
박민수  75   80   85   240   80.0
과목평균 83.3 85.0 86.7
</code></pre><h3 id="문제-3-행렬-회전">문제 3: 행렬 회전</h3>
<p>N x N 크기의 2차원 리스트(행렬)를 시계 방향으로 90도 회전시키는 함수를 작성하세요.</p>
<pre><code>예시:
원본 행렬:
1 2 3
4 5 6
7 8 9

90도 회전 후:
7 4 1
8 5 2
9 6 3
</code></pre><h2 id="딕셔너리-문제">딕셔너리 문제</h2>
<h3 id="문제-4-단어-빈도수-계산">문제 4: 단어 빈도수 계산</h3>
<p>주어진 문장에서 각 단어의 등장 횟수를 계산하여 딕셔너리로 반환하는 함수를 작성하세요. 대소문자는 구분하지 않고, 특수문자는 제외합니다.</p>
<pre><code>예시:
sentence = &quot;Python is easy to learn. Python is popular and Python is powerful.&quot;

결과: {&#39;python&#39;: 3, &#39;is&#39;: 3, &#39;easy&#39;: 1, &#39;to&#39;: 1, &#39;learn&#39;: 1, &#39;popular&#39;: 1, &#39;and&#39;: 1, &#39;powerful&#39;: 1}
</code></pre><h3 id="문제-5-투표-결과-집계">문제 5: 투표 결과 집계</h3>
<p>선거에서 투표한 결과를 리스트로 받아, 각 후보자별 득표수를 딕셔너리로 반환하고, 가장 많은 표를 받은 후보자를 출력하는 프로그램을 작성하세요.</p>
<pre><code>예시:
votes = [&quot;김후보&quot;, &quot;이후보&quot;, &quot;김후보&quot;, &quot;박후보&quot;, &quot;이후보&quot;, &quot;김후보&quot;, &quot;최후보&quot;, &quot;김후보&quot;, &quot;이후보&quot;, &quot;박후보&quot;]

결과:
투표 결과: {&#39;김후보&#39;: 4, &#39;이후보&#39;: 3, &#39;박후보&#39;: 2, &#39;최후보&#39;: 1}
당선인: 김후보 (4표)
</code></pre><h3 id="문제-6-학생-성적-관리">문제 6: 학생 성적 관리</h3>
<p>학생들의 성적을 관리하는 프로그램을 작성하세요. 다음 기능을 구현하세요:</p>
<ol>
<li>학생 추가: 이름과 성적(국어, 영어, 수학)을 입력받아 딕셔너리에 저장</li>
<li>학생 검색: 이름으로 학생을 검색하여 성적 정보 출력</li>
<li>전체 학생 출력: 모든 학생의 이름과 성적, 평균 출력</li>
<li>평균 순위로 정렬하여 출력</li>
</ol>
<h2 id="복합-문제">복합 문제</h2>
<h3 id="문제-7-도서-관리-시스템">문제 7: 도서 관리 시스템</h3>
<p>도서관에서 사용할 도서 관리 시스템을 구현하세요. 다음 기능을 포함해야 합니다:</p>
<ol>
<li>도서 등록: 제목, 저자, 출판년도, 장르 정보를 딕셔너리로 저장</li>
<li>도서 검색: 제목 또는 저자로 도서 검색</li>
<li>도서 대출/반납 처리: 대출 상태를 관리하고 대출 중인 도서 목록 확인</li>
<li>장르별 도서 목록 출력: 특정 장르의 모든 도서를 출력</li>
</ol>
<h3 id="문제-8-주간-일정-관리">문제 8: 주간 일정 관리</h3>
<p>요일별 일정을 관리하는 프로그램을 작성하세요. 2차원 리스트와 딕셔너리를 활용하여 다음 기능을 구현하세요:</p>
<ol>
<li>일정 추가: 요일, 시간, 일정 내용을 입력받아 저장</li>
<li>일정 삭제: 요일과 시간을 입력받아 해당 일정 삭제</li>
<li>요일별 일정 출력: 특정 요일의 모든 일정을 시간순으로 출력</li>
<li>주간 요약: 전체 주간 일정을 표 형식으로 출력</li>
</ol>
<h2 id="답안-작성-제출-양식">답안 작성 제출 양식</h2>
<p>문제 풀이 시, 다음 형식으로 답안을 작성하세요:</p>
<ol>
<li>문제 이해: 문제가 요구하는 사항을 자신의 말로 간략히 설명</li>
<li>알고리즘/접근법: 문제 해결을 위한 접근 방식 설명</li>
<li>코드 구현: 파이썬 코드 작성</li>
<li>결과 확인: 예시 입력값으로 실행한 결과</li>
<li>코드 설명: 주요 부분에 대한 간략한 설명</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter08. 리스트 메소드]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter08.-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EB%A9%94%EC%86%8C%EB%93%9C-ghk1pqhf</link>
            <guid>https://velog.io/@lullaby_/PythonChapter08.-%EB%A6%AC%EC%8A%A4%ED%8A%B8-%EB%A9%94%EC%86%8C%EB%93%9C-ghk1pqhf</guid>
            <pubDate>Wed, 01 Oct 2025 01:22:18 GMT</pubDate>
            <description><![CDATA[<h2 id="1-리스트-기본-개념">1. 리스트 기본 개념</h2>
<p>리스트는 파이썬에서 여러 항목을 순서대로 저장하는 시퀀스 자료형입니다. 대괄호 <code>[]</code>로 표현하며, 다양한 데이터 타입을 함께 저장할 수 있습니다.</p>
<h3 id="리스트-생성-및-접근">리스트 생성 및 접근:</h3>
<pre><code class="language-python"># 리스트 생성
heroes = [&quot;스파이더맨&quot;, &quot;헐크&quot;, &quot;아이언맨&quot;]

# 리스트 요소 접근
first_hero = heroes[0]  # &quot;스파이더맨&quot;
</code></pre>
<h2 id="2-리스트의-주요-연산과-함수">2. 리스트의 주요 연산과 함수</h2>
<h3 id="기본-연산자-및-함수">기본 연산자 및 함수</h3>
<table>
<thead>
<tr>
<th>연산자/함수</th>
<th>설명</th>
<th>예시</th>
<th>결과</th>
</tr>
</thead>
<tbody><tr>
<td><code>len()</code></td>
<td>길이 계산</td>
<td><code>len([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;])</code></td>
<td><code>3</code></td>
</tr>
<tr>
<td><code>+</code></td>
<td>두 리스트 연결</td>
<td><code>[1, 2] + [3, 4]</code></td>
<td><code>[1, 2, 3, 4]</code></td>
</tr>
<tr>
<td><code>*</code></td>
<td>리스트 반복//주의!!!! 리스트가 ([1,2]가)3번 반복되어 리스트안에 리스트로 들어가는 게 아니라 리스트안에있는 양이 배가됨</td>
<td><code>[1, 2] * 3</code></td>
<td><code>[1, 2, 1, 2, 1, 2]</code></td>
</tr>
<tr>
<td><code>in</code></td>
<td>요소가 포함되어 있는지</td>
<td><code>&quot;a&quot; in [&quot;a&quot;, &quot;b&quot;]</code></td>
<td><code>True</code></td>
</tr>
<tr>
<td><code>not in</code></td>
<td>요소가 포함되어 있지 않은지</td>
<td><code>&quot;c&quot; not in [&quot;a&quot;, &quot;b&quot;]</code></td>
<td><code>True</code></td>
</tr>
<tr>
<td><code>min()</code></td>
<td>최소값 찾기</td>
<td><code>min([5, 1, 3])</code></td>
<td><code>1</code></td>
</tr>
<tr>
<td><code>max()</code></td>
<td>최대값 찾기</td>
<td><code>max([5, 1, 3])</code></td>
<td><code>5</code></td>
</tr>
<tr>
<td><code>sum()</code></td>
<td>모든 요소의 합</td>
<td><code>sum([1, 2, 3])</code></td>
<td><code>6</code></td>
</tr>
</tbody></table>
<h3 id="예제-코드">예제 코드:</h3>
<pre><code class="language-python">marvel_heroes = [&quot;스파이더맨&quot;, &quot;헐크&quot;, &quot;아이언맨&quot;]
dc_heroes = [&quot;슈퍼맨&quot;, &quot;배트맨&quot;, &quot;원더우먼&quot;]

# 리스트 연결
heroes = marvel_heroes + dc_heroes
print(heroes)  # [&#39;스파이더맨&#39;, &#39;헐크&#39;, &#39;아이언맨&#39;, &#39;슈퍼맨&#39;, &#39;배트맨&#39;, &#39;원더우먼&#39;]

# 리스트 반복
values = [1, 2, 3] * 3
print(values)  # [1, 2, 3, 1, 2, 3, 1, 2, 3]

# 리스트 길이
print(len(heroes))  # 6

# 포함 여부 확인
if &quot;배트맨&quot; in heroes:
    print(&quot;배트맨은 영웅입니다.&quot;)  # 출력됨

# 최소/최대/합계
numbers = [11, 2, 13, 4, 5]
print(min(numbers))  # 2
print(max(numbers))  # 13
print(sum(numbers))  # 35
</code></pre>
<h2 id="3-리스트-메소드">3. 리스트 메소드</h2>
<table>
<thead>
<tr>
<th>메소드</th>
<th>설명</th>
</tr>
</thead>
<tbody><tr>
<td><code>append(item)</code></td>
<td>리스트 끝에 항목 추가</td>
</tr>
<tr>
<td><code>insert(index, item)</code></td>
<td>특정 위치에 항목 삽입</td>
</tr>
<tr>
<td><code>remove(item)</code></td>
<td>특정 항목 삭제</td>
</tr>
<tr>
<td><code>pop([index])</code></td>
<td>특정 위치의 항목 제거 후 반환 (기본값: 마지막 항목) =⇒걍 숫자넣으면 해당인덱스항목 삭제됨</td>
</tr>
<tr>
<td><code>index(item)</code></td>
<td>특정 항목의 위치 반환</td>
</tr>
<tr>
<td><code>sort()</code></td>
<td>원본 리스트 정렬</td>
</tr>
<tr>
<td><code>reverse()</code></td>
<td>원본 리스트 역순 정렬</td>
</tr>
<tr>
<td><code>count(item)</code></td>
<td>특정 항목의 개수 반환</td>
</tr>
<tr>
<td><code>clear()</code></td>
<td>모든 항목 삭제</td>
</tr>
</tbody></table>
<h3 id="예제-코드-1">예제 코드:</h3>
<pre><code class="language-python"># 항목 추가
shopping_list = []
shopping_list.append(&quot;두부&quot;)
shopping_list.append(&quot;양배추&quot;)
print(shopping_list)  # [&#39;두부&#39;, &#39;양배추&#39;]

# 특정 위치에 항목 삽입
a = [1, 2, 3]
a.insert(0, 4)  # 0번 위치에 4 삽입
print(a)  # [4, 1, 2, 3]

# 항목 삭제
heroes = [&quot;스파이더맨&quot;, &quot;슈퍼맨&quot;, &quot;헐크&quot;, &quot;아이언맨&quot;, &quot;배트맨&quot;, &quot;조커&quot;]
heroes.remove(&quot;조커&quot;)
print(heroes)  # [&#39;스파이더맨&#39;, &#39;슈퍼맨&#39;, &#39;헐크&#39;, &#39;아이언맨&#39;, &#39;배트맨&#39;]

# pop으로 항목 삭제 및 반환
hero = heroes.pop(1)  # &#39;슈퍼맨&#39;
print(hero)  # &#39;슈퍼맨&#39;
print(heroes)  # [&#39;스파이더맨&#39;, &#39;헐크&#39;, &#39;아이언맨&#39;, &#39;배트맨&#39;]

# 항목 위치 확인
index = heroes.index(&quot;헐크&quot;)
print(index)  # 1

# 정렬
numbers = [3, 2, 1, 5, 4]
numbers.sort()  # 원본 리스트 변경
print(numbers)  # [1, 2, 3, 4, 5]

# 내림차순 정렬
numbers.sort(reverse=True)
print(numbers)  # [5, 4, 3, 2, 1]

# sorted() 함수 (원본 리스트 유지하며 정렬된 새 리스트 반환)
a = [3, 2, 1, 5, 4]
b = sorted(a)
print(b)  # [1, 2, 3, 4, 5]
print(a)  # [3, 2, 1, 5, 4] - 원본 유지
</code></pre>
<h2 id="4-리스트-복사">4. 리스트 복사</h2>
<h3 id="얕은-복사shallow-copy">얕은 복사(Shallow copy)</h3>
<pre><code class="language-python">scores = [10, 20, 30, 40, 50]
values = scores  # 얕은 복사 - 동일한 객체를 참조
print(id(scores))  # 메모리 주소
print(id(values))  # scores와 동일한 메모리 주소

# 하나의 리스트를 변경하면 다른 리스트도 변경됨
scores[0] = 99
print(values)  # [99, 20, 30, 40, 50]
</code></pre>
<h3 id="깊은-복사deep-copy">깊은 복사(Deep copy)</h3>
<pre><code class="language-python">import copy
a = [1, 2, 3, 4]
b = copy.deepcopy(a)  # 깊은 복사 - 새로운 객체 생성

# 메모리 주소 다름
print(id(a))  # 첫 번째 메모리 주소
print(id(b))  # 두 번째 메모리 주소

# 한 리스트 변경해도 다른 리스트는 영향 없음
a.append(500)
print(a)  # [1, 2, 3, 4, 500]
print(b)  # [1, 2, 3, 4]
</code></pre>
<h2 id="5-리스트-컴프리헨션list-comprehension-함축">5. 리스트 컴프리헨션(List Comprehension), 함축!!</h2>
<p>리스트 컴프리헨션은 리스트를 간결하게 생성하는 방법입니다.</p>
<h3 id="기본-구문">기본 구문:</h3>
<pre><code>[표현식 for 항목 in 반복가능객체 if 조건문]
</code></pre><h3 id="예제-코드-2">예제 코드:</h3>
<pre><code class="language-python"># 기본 리스트 컴프리헨션
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 기존 리스트 변환
list1 = [3, 4, 5]
list2 = [x*2 for x in list1]
print(list2)  # [6, 8, 10]

# 조건문 사용
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)  # [0, 2, 4, 6, 8]

# 다중 반복문
pythagorean_triples = [(x, y, z) for x in range(1, 21)
                       for y in range(x, 21)
                       for z in range(y, 21)
                       if x**2 + y**2 == z**2]
print(pythagorean_triples)  # [(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15)]
</code></pre>
<h2 id="6-함수에서의-리스트-전달">6. 함수에서의 리스트 전달</h2>
<p>파이썬에서 리스트를 함수에 전달하면 참조 방식으로 전달됩니다. 즉, 함수 내에서 리스트를 변경하면 원본 리스트도 변경됩니다.</p>
<pre><code class="language-python">def modify_list(lst):
    lst[0] = 99

values = [0, 1, 2, 3, 4]
print(&quot;함수 호출 전:&quot;, values)  # [0, 1, 2, 3, 4]
modify_list(values)
print(&quot;함수 호출 후:&quot;, values)  # [99, 1, 2, 3, 4]
</code></pre>
<h2 id="7-실전-예제-프로그램">7. 실전 예제 프로그램</h2>
<h3 id="예제-1-성적-처리-프로그램">예제 1: 성적 처리 프로그램</h3>
<pre><code class="language-python">STUDENTS = 5
scores = []
scoreSum = 0

# 성적 입력 받기
for i in range(STUDENTS):
    value = int(input(&quot;성적을 입력하시오: &quot;))
    scores.append(value)
    scoreSum += value

# 평균 계산
scoreAvg = scoreSum / len(scores)

# 80점 이상 학생 수 계산
highScoreStudents = 0
for score in scores:
    if score &gt;= 80:
        highScoreStudents += 1

# 결과 출력
print(&quot;성적 평균은&quot;, scoreAvg, &quot;입니다.&quot;)
print(&quot;80점 이상 성적을 받은 학생은&quot;, highScoreStudents, &quot;명입니다.&quot;)
</code></pre>
<h3 id="예제-2-연락처-관리-프로그램">예제 2: 연락처 관리 프로그램</h3>
<pre><code class="language-python">menu = 0
friends = []

while menu != 9:
    print(&quot;--------------------&quot;)
    print(&quot;1. 친구 리스트 출력&quot;)
    print(&quot;2. 친구 추가&quot;)
    print(&quot;3. 친구 삭제&quot;)
    print(&quot;4. 이름 변경&quot;)
    print(&quot;9. 종료&quot;)

    menu = int(input(&quot;메뉴를 선택하시오: &quot;))

    if menu == 1:
        print(friends)
    elif menu == 2:
        name = input(&quot;이름을 입력하시오: &quot;)
        friends.append(name)
    elif menu == 3:
        del_name = input(&quot;삭제하고 싶은 이름을 입력하시오: &quot;)
        if del_name in friends:
            friends.remove(del_name)
        else:
            print(&quot;이름이 발견되지 않았음&quot;)
    elif menu == 4:
        old_name = input(&quot;변경하고 싶은 이름을 입력하시오: &quot;)
        if old_name in friends:
            index = friends.index(old_name)
            new_name = input(&quot;새로운 이름을 입력하시오: &quot;)
            friends[index] = new_name
        else:
            print(&quot;이름이 발견되지 않았음&quot;)
</code></pre>
<h2 id="8-중간고사-예상-문제-및-풀이">8. 중간고사 예상 문제 및 풀이</h2>
<h1 id="파이썬-리스트-중간고사-예상-문제-및-풀이">파이썬 리스트 중간고사 예상 문제 및 풀이</h1>
<h2 id="객관식-문제">객관식 문제</h2>
<h3 id="문제-1">문제 1</h3>
<p>다음 중 리스트 <code>a = [1, 2, 3, 4, 5]</code>를 복제하여 새로운 리스트 <code>b</code>를 만들고 싶을 때, 독립적인 복사본(깊은 복사)을 만드는 올바른 방법은?</p>
<p>a) <code>b = a</code>
b) <code>b = a[:]</code>
c) <code>b = copy.deepcopy(a)</code>
d) <code>b = list(a)</code></p>
<p><strong>정답: c) <code>b = copy.deepcopy(a)</code></strong></p>
<p><strong>해설:</strong></p>
<ul>
<li><code>b = a</code>는 새로운 리스트를 만드는 것이 아니라 같은 객체를 참조(얕은 복사)합니다.</li>
<li><code>b = a[:]</code>와 <code>b = list(a)</code>는 1차원 리스트의 경우 독립적인 복사본을 만들지만, 중첩 리스트의 경우 내부 리스트는 여전히 같은 객체를 참조합니다.</li>
<li><code>copy.deepcopy(a)</code>는 중첩 리스트를 포함한 모든 구조를 완전히 독립적으로 복사합니다.</li>
</ul>
<h3 id="문제-2">문제 2</h3>
<p>다음 코드의 실행 결과는?</p>
<pre><code class="language-python">values = [1, 2, 3]
values.append([4, 5])
print(len(values))
</code></pre>
<p>a) 3
b) 4
c) 5
d) 오류 발생</p>
<p><strong>정답: b) 4</strong></p>
<p><strong>해설:</strong> <code>values.append([4, 5])</code>는 리스트 <code>[4, 5]</code>를 하나의 요소로 <code>values</code> 리스트에 추가합니다. 따라서 <code>values</code>는 <code>[1, 2, 3, [4, 5]]</code>가 되고, 길이는 4가 됩니다.</p>
<h3 id="문제-3">문제 3</h3>
<p>다음 코드의 실행 결과는?</p>
<pre><code class="language-python">numbers = [1, 2, 3, 4, 5]
print(numbers[1:-1])
</code></pre>
<p>a) [1, 2, 3, 4]
b) [2, 3, 4]
c) [2, 3, 4, 5]
d) [1, 2, 3]</p>
<p><strong>정답: b) [2, 3, 4]</strong></p>
<p><strong>해설:</strong> <code>numbers[1:-1]</code>은 인덱스 1부터 마지막 인덱스(-1) 바로 전까지의 요소를 반환합니다. 인덱스 1은 2, 인덱스 -1은 5이므로, 2부터 5 직전까지인 [2, 3, 4]가 출력됩니다.</p>
<h3 id="문제-4">문제 4</h3>
<p>다음 중 리스트 메소드가 <strong>아닌</strong> 것은?</p>
<p>a) <code>append()</code>
b) <code>insert()</code>
c) <code>add()</code>
d) <code>remove()</code></p>
<p><strong>정답: c) <code>add()</code></strong></p>
<p><strong>해설:</strong> 파이썬 리스트에는 <code>add()</code> 메소드가 존재하지 않습니다. 요소를 추가하는 메소드는 <code>append()</code>(끝에 추가), <code>insert()</code>(지정된 위치에 추가), <code>extend()</code>(반복 가능한 객체의 요소를 추가)입니다.</p>
<h3 id="문제-5">문제 5</h3>
<p>다음 코드의 출력은?</p>
<pre><code class="language-python">a = [3, 2, 1, 5, 4]
b = a.sort()
print(b)
</code></pre>
<p>a) [1, 2, 3, 4, 5]
b) [3, 2, 1, 5, 4]
c) None
d) 오류 발생</p>
<p><strong>정답: c) None</strong></p>
<p><strong>해설:</strong> <code>sort()</code> 메소드는 원본 리스트를 제자리에서 정렬하고 아무것도 반환하지 않습니다(None 반환). 따라서 b에는 None이 할당되고, 이것이 출력됩니다. 정렬된 리스트를 반환받으려면 <code>sorted()</code> 함수를 사용해야 합니다.</p>
<h2 id="서술형-및-코딩-문제">서술형 및 코딩 문제</h2>
<h3 id="문제-6">문제 6</h3>
<p>다음 조건을 만족하는 리스트 컴프리헨션을 작성하세요:</p>
<ol>
<li>1부터 50까지의 정수 중</li>
<li>3의 배수이면서</li>
<li>5의 배수가 아닌 수</li>
</ol>
<p><strong>정답:</strong></p>
<pre><code class="language-python">result = [x for x in range(1, 51) if x % 3 == 0 and x % 5 != 0]
</code></pre>
<h3 id="문제-7">문제 7</h3>
<p>다음 코드가 출력하는 결과를 쓰세요:</p>
<pre><code class="language-python">heroes = [&quot;아이언맨&quot;, &quot;토르&quot;, &quot;헐크&quot;, &quot;스파이더맨&quot;]
heroes.pop(1)
heroes.insert(0, &quot;블랙위도우&quot;)
heroes.append(&quot;캡틴아메리카&quot;)
print(heroes)
</code></pre>
<p><strong>정답:</strong> <code>[&#39;블랙위도우&#39;, &#39;아이언맨&#39;, &#39;헐크&#39;, &#39;스파이더맨&#39;, &#39;캡틴아메리카&#39;]</code></p>
<p><strong>해설:</strong></p>
<ol>
<li>초기 <code>heroes</code> = [&quot;아이언맨&quot;, &quot;토르&quot;, &quot;헐크&quot;, &quot;스파이더맨&quot;]</li>
<li><code>heroes.pop(1)</code>로 인덱스 1의 &quot;토르&quot; 제거 → [&quot;아이언맨&quot;, &quot;헐크&quot;, &quot;스파이더맨&quot;]</li>
<li><code>heroes.insert(0, &quot;블랙위도우&quot;)</code>로 인덱스 0에 &quot;블랙위도우&quot; 삽입 → [&quot;블랙위도우&quot;, &quot;아이언맨&quot;, &quot;헐크&quot;, &quot;스파이더맨&quot;]</li>
<li><code>heroes.append(&quot;캡틴아메리카&quot;)</code>로 끝에 &quot;캡틴아메리카&quot; 추가 → [&quot;블랙위도우&quot;, &quot;아이언맨&quot;, &quot;헐크&quot;, &quot;스파이더맨&quot;, &quot;캡틴아메리카&quot;]</li>
</ol>
<h3 id="문제-8">문제 8</h3>
<p>다음 코드의 출력을 예측하세요:</p>
<pre><code class="language-python">def modify_scores(scores):
    scores.append(100)
    scores = [50, 60, 70]
    scores.append(80)
    return scores

my_scores = [85, 90, 95]
new_scores = modify_scores(my_scores)
print(my_scores)
print(new_scores)
</code></pre>
<p><strong>정답:</strong></p>
<pre><code>[85, 90, 95, 100]
[50, 60, 70, 80]
</code></pre><p><strong>해설:</strong></p>
<ol>
<li><code>my_scores</code>가 <code>modify_scores</code> 함수에 전달됩니다.</li>
<li>함수 내에서 <code>scores.append(100)</code>로 <code>my_scores</code>에 100 추가 → <code>my_scores</code> = [85, 90, 95, 100]</li>
<li><code>scores = [50, 60, 70]</code>으로 <code>scores</code> 변수에 새 리스트 할당. 하지만 이것은 <code>my_scores</code>에 영향을 주지 않습니다.</li>
<li><code>scores.append(80)</code>으로 새 리스트에 80 추가 → <code>scores</code> = [50, 60, 70, 80]</li>
<li>함수는 <code>scores</code> 리스트를 반환하므로 <code>new_scores</code> = [50, 60, 70, 80]</li>
<li><code>my_scores</code>에는 첫 번째 <code>append</code> 작업만 영향을 주었으므로 [85, 90, 95, 100]이 됩니다.</li>
</ol>
<h3 id="문제-9">문제 9</h3>
<p>다음 리스트에서 중복된 요소를 제거하여 유일한 값만 가진 새 리스트를 반환하는 함수를 작성하세요. 원본 리스트 순서를 유지해야 합니다. (힌트: 이미 확인한 요소를 기록하는 새 리스트를 사용하세요)</p>
<pre><code class="language-python">def remove_duplicates(input_list):
    # 코드 작성
    pass
</code></pre>
<p><strong>정답:</strong></p>
<pre><code class="language-python">def remove_duplicates(input_list):
    result = []
    for item in input_list:
        if item not in result:
            result.append(item)
    return result
</code></pre>
<p><strong>또는 리스트 컴프리헨션 사용:</strong></p>
<pre><code class="language-python">def remove_duplicates(input_list):
    seen = set()
    return [x for x in input_list if not (x in seen or seen.add(x))]
</code></pre>
<h3 id="문제-10">문제 10</h3>
<p>피보나치 수열의 처음 20개 항을 계산하여 리스트에 저장하는 코드를 작성하세요. 피보나치 수열은 0, 1로 시작하고, 다음 항은 이전 두 항의 합으로 구성됩니다.</p>
<p><strong>정답:</strong></p>
<pre><code class="language-python">fibonacci = [0, 1]
for i in range(2, 20):
    fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
print(fibonacci)
</code></pre>
<p><strong>또는 리스트 컴프리헨션 사용 (조금 더 복잡):</strong></p>
<pre><code class="language-python">fibonacci = [0, 1]
[fibonacci.append(fibonacci[-1] + fibonacci[-2]) for _ in range(18)]
print(fibonacci)
</code></pre>
<h3 id="문제-11">문제 11</h3>
<p>리스트의 모든 가능한 두 요소의 조합과 그 합을 계산하는 프로그램을 작성하세요. 출력은 튜플 리스트 <code>[(a, b, a+b), ...]</code> 형태여야 합니다.</p>
<p>입력: <code>[1, 2, 3, 4]</code>
출력: <code>[(1, 2, 3), (1, 3, 4), (1, 4, 5), (2, 3, 5), (2, 4, 6), (3, 4, 7)]</code></p>
<p><strong>정답:</strong></p>
<pre><code class="language-python">def all_combinations(numbers):
    result = []
    for i in range(len(numbers)):
        for j in range(i+1, len(numbers)):
            result.append((numbers[i], numbers[j], numbers[i] + numbers[j]))
    return result

print(all_combinations([1, 2, 3, 4]))
</code></pre>
<p><strong>또는 리스트 컴프리헨션 사용:</strong></p>
<pre><code class="language-python">def all_combinations(numbers):
    return [(numbers[i], numbers[j], numbers[i] + numbers[j])
            for i in range(len(numbers))
            for j in range(i+1, len(numbers))]

print(all_combinations([1, 2, 3, 4]))
</code></pre>
<h3 id="문제-12">문제 12</h3>
<p>다음과 같은 학생 성적 리스트가 있습니다: <code>scores = [78, 65, 89, 93, 87, 45, 92]</code>
평균보다 높은 점수만 출력하는 코드를 작성하세요.</p>
<p><strong>정답:</strong></p>
<pre><code class="language-python">scores = [78, 65, 89, 93, 87, 45, 92]
average = sum(scores) / len(scores)
above_average = [score for score in scores if score &gt; average]
print(f&quot;평균: {average}&quot;)
print(f&quot;평균보다 높은 점수: {above_average}&quot;)
</code></pre>
<h2 id="9-중간고사-실전-대비-tip">9. 중간고사 실전 대비 TIP</h2>
<h3 id="리스트-관련-주요-개념-정리">리스트 관련 주요 개념 정리</h3>
<ul>
<li><strong>리스트 기본 연산</strong>: <code>+</code>, , <code>in</code>, <code>not in</code> 등의 사용법 숙지</li>
<li><strong>리스트 주요 메소드</strong>: <code>append()</code>, <code>insert()</code>, <code>remove()</code>, <code>pop()</code>, <code>index()</code>, <code>sort()</code> 등의 기능과 사용법 숙지</li>
<li><strong>리스트 슬라이싱</strong>: 인덱싱과 슬라이싱 문법 확실히 이해</li>
<li><strong>리스트 복사 방식</strong>: 얕은 복사와 깊은 복사의 차이점 명확히 이해</li>
<li><strong>리스트 컴프리헨션</strong>: 기본 구조와 응용 방법 연습</li>
</ul>
<h3 id="실전-대비-전략">실전 대비 전략</h3>
<ol>
<li><strong>개념 이해하기</strong>: 각 리스트 메소드와 함수의 역할, 반환값을 분명히 이해하세요.</li>
<li><strong>손으로 코드 실행해보기</strong>: 복잡한 리스트 조작이 있는 코드는 손으로 한 줄씩 실행해보며 결과를 예측해보세요.</li>
<li><strong>문제 풀이 시간 배분하기</strong>: 쉬운 문제를 먼저 풀고 어려운 문제에 시간을 투자하세요.</li>
<li><strong>코드 트레이싱 연습하기</strong>: 주어진 코드가 어떤 결과를 내는지 단계별로 예측하는 연습을 하세요.</li>
<li><strong>리스트 컴프리헨션 활용하기</strong>: 간결하고 가독성 높은 코드 작성을 위해 리스트 컴프리헨션을 적절히 활용하세요.</li>
</ol>
<h3 id="자주-나오는-실수">자주 나오는 실수</h3>
<ul>
<li><strong>인덱스 오류</strong>: 리스트 범위를 벗어나는 인덱스 접근</li>
<li><strong>얕은 복사와 깊은 복사 혼동</strong>: 의도와 다른 복사 방식 사용</li>
<li><strong>메소드의 반환값 무시</strong>: <code>sort()</code>와 <code>sorted()</code>의 차이 혼동</li>
<li><strong>리스트 변경 시 참조 문제</strong>: 함수에서 리스트를 변경할 때 발생하는 문제 인지 부족</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter06. 문자열]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter06.-%EB%AC%B8%EC%9E%90%EC%97%B4-40h2hnxm</link>
            <guid>https://velog.io/@lullaby_/PythonChapter06.-%EB%AC%B8%EC%9E%90%EC%97%B4-40h2hnxm</guid>
            <pubDate>Wed, 01 Oct 2025 01:19:55 GMT</pubDate>
            <description><![CDATA[<h2 id="1-문자열-기본-개념">1. 문자열 기본 개념</h2>
<h3 id="핵심-정의">핵심 정의</h3>
<ul>
<li>문자열(string)은 문자들의 <strong>순서 있는 집합</strong></li>
<li>문자들이 끈으로 묶여 있는 형태로 이해 가능</li>
<li>파이썬에서 문자열은 따옴표(<code>&#39;</code> 또는 <code>&quot;</code>)로 둘러싸여 표현</li>
</ul>
<h3 id="중요성">중요성</h3>
<ul>
<li>컴퓨터는 숫자 중심이지만, 인간은 문자열을 통해 정보 표현</li>
<li>문자열 처리는 프로그래밍에서 매우 중요한 부분</li>
</ul>
<h2 id="2-문자열-생성과-기본-표현">2. 문자열 생성과 기본 표현</h2>
<h3 id="문자열-선언-방법">문자열 선언 방법</h3>
<pre><code class="language-python">greeting = &quot;Merry Christmas!&quot;  # 큰따옴표 사용
greeting = &#39;Happy Holiday!&#39;    # 작은따옴표 사용
</code></pre>
<h3 id="여러-줄-문자열">여러 줄 문자열</h3>
<pre><code class="language-python">greeting = &#39;&#39;&#39;지난 한해 저에게 보여주신 보살핌과 사랑에
깊은 감사를 드립니다.
새해에도 하시고자 하는 일
모두 성취하시기를 바랍니다.&#39;&#39;&#39;
</code></pre>
<h3 id="따옴표-처리">따옴표 처리</h3>
<pre><code class="language-python"># 큰따옴표 안에 작은따옴표 사용
message = &quot;철수가 &#39;안녕&#39;이라고 말했습니다.&quot;

# 작은따옴표 안에 큰따옴표 사용
message = &#39;철수가 &quot;안녕&quot;이라고 말했습니다.&#39;

# 이스케이프 문자 사용
message = &quot;\&quot;Yes,\&quot; he said.&quot;  # 큰따옴표 출력
message = &#39;doesn\&#39;t&#39;           # 작은따옴표 출력
</code></pre>
<h2 id="3-문자열-연산">3. 문자열 연산</h2>
<h3 id="문자열-연결-">문자열 연결 (+)</h3>
<pre><code class="language-python">&quot;Py&quot; + &quot;thon&quot;    # &#39;Python&#39;
&#39;Harry &#39; + &#39;Potter&#39;  # &#39;Harry Potter&#39;

# 변수 사용
first_name = &quot;길동&quot;
last_name = &quot;홍&quot;
name = last_name + first_name  # &#39;홍길동&#39;
</code></pre>
<h3 id="문자열과-숫자-연결">문자열과 숫자 연결</h3>
<pre><code class="language-python"># 숫자를 문자열로 변환 후 연결
print(&quot;student&quot; + str(26))  # &#39;student26&#39;

# 문자열을 숫자로 변환
price = int(&quot;3000&quot;)  # 3000 (정수)
height = float(&quot;290.54&quot;)  # 290.54 (실수)
</code></pre>
<h3 id="문자열-반복-">문자열 반복 (*)</h3>
<pre><code class="language-python">line = &quot;=&quot; * 50  # 50개의 등호(=) 반복
message = &quot;Congratulations! &quot; * 3  # &#39;Congratulations! &#39; 3번 반복
</code></pre>
<h2 id="4-문자열-서식">4. 문자열 서식</h2>
<h3 id="형식-지정자-s">형식 지정자 (%s)</h3>
<pre><code class="language-python">price = 10000
print(&quot;상품의 가격은 %s원입니다.&quot; % price)  # 상품의 가격은 10000원입니다.

message = &quot;현재 시간은 %s입니다.&quot;
time = &quot;12:00pm&quot;
print(message % time)  # 현재 시간은 12:00pm입니다.
</code></pre>
<h2 id="5-문자열-메소드">5. 문자열 메소드</h2>
<h3 id="탐색-관련-메소드">탐색 관련 메소드</h3>
<pre><code class="language-python">s = &quot;Love will find a way.&quot;
&quot;Love&quot; in s      # True
&quot;love&quot; in s      # False - 대소문자 구분
&quot;Love&quot; not in s  # False
</code></pre>
<h3 id="문자-유형-확인-메소드">문자 유형 확인 메소드</h3>
<pre><code class="language-python">num = &#39;111&#39;
baeg = &#39;hundred&#39;
hanguel = &#39;한글&#39;
space = &#39; &#39;

num.isdigit()     # True - 숫자인지 확인
baeg.isalpha()    # True - 알파벳(문자)인지 확인
hanguel.isalpha() # True - 문자인지 확인
space.isspace()   # True - 공백인지 확인
</code></pre>
<h3 id="분리와-결합-메소드">분리와 결합 메소드</h3>
<pre><code class="language-python"># split() - 문자열을 구분자로 분리하여 **리스트로** 반환
&quot;Life is too short&quot;.split()  # [&#39;Life&#39;, &#39;is&#39;, &#39;too&#39;, &#39;short&#39;]
&quot;a:b:c:d&quot;.split(&#39;:&#39;)         # [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]
</code></pre>
<h3 id="공백-제거-메소드">공백 제거 메소드</h3>
<pre><code class="language-python">s = &#39; Python &#39;
s.lstrip()  # &#39;Python &#39; - 왼쪽 공백 제거
s.rstrip()  # &#39; Python&#39; - 오른쪽 공백 제거
s.strip()   # &#39;Python&#39; - 양쪽 공백 제거
</code></pre>
<h3 id="대소문자-변환-메소드">대소문자 변환 메소드</h3>
<pre><code class="language-python">&#39;python&#39;.upper()  # &#39;PYTHON&#39; - 대문자로 변환
&#39;PYTHON&#39;.lower()  # &#39;python&#39; - 소문자로 변환
</code></pre>
<h3 id="문자-코드-변환">문자 코드 변환</h3>
<pre><code class="language-python">ord(&quot;A&quot;)  # 65 - 문자를 ASCII 코드 값으로 변환
chr(65)   # &#39;A&#39; - ASCII 코드 값을 문자로 변환
</code></pre>
<h3 id="문자열-치환">문자열 치환</h3>
<pre><code class="language-python">text = &#39;123,456,789,999&#39;
text.replace(&quot;,&quot;, &quot;&quot;)    # &#39;123456789999&#39; - 모든 콤마 제거
text.replace(&quot;,&quot;, &quot;&quot;, 1) # &#39;123456,789,999&#39; - 첫 번째 콤마만 제거
</code></pre>
<h2 id="6-문자열-인덱싱과-슬라이싱">6. 문자열 인덱싱과 슬라이싱</h2>
<h3 id="인덱싱">인덱싱</h3>
<pre><code class="language-python">word = &#39;Python&#39;
word[0]   # &#39;P&#39; - 첫 번째 문자
word[5]   # &#39;n&#39; - 여섯 번째 문자
word[-1]  # &#39;n&#39; - 마지막 문자 (음수 인덱스)
</code></pre>
<h3 id="슬라이싱">슬라이싱</h3>
<pre><code class="language-python">word = &#39;Python&#39;
word[0:2]  # &#39;Py&#39; - 0부터 1까지
word[2:5]  # &#39;tho&#39; - 2부터 4까지
</code></pre>
<h2 id="7-실전-문제-풀이-예제">7. 실전 문제 풀이 예제</h2>
<h3 id="예제-1-두문자어acronym-만들기">예제 1: 두문자어(acronym) 만들기</h3>
<pre><code class="language-python"># 여러 단어로 된 문자열에서 각 단어의 첫 글자로 두문자어 만들기
phrase = input(&quot;문자열을 입력하시오: &quot;)  # 예: &quot;Programming Language Theory&quot;
acronym = &quot;&quot;
for word in phrase.upper().split():
    acronym += word[0]
print(&quot;acronym :&quot;, acronym)  # &quot;PLT&quot;
</code></pre>
<h3 id="예제-2-모음-제거하기">예제 2: 모음 제거하기</h3>
<pre><code class="language-python">s = input(&#39;문자열을 입력하시오: &#39;)  # 예: &quot;hello&quot;
vowels = &quot;aeiouAEIOU&quot;
result = &quot;&quot;
for letter in s:
    if letter not in vowels:
        result += letter
print(result)  # &quot;hll&quot;
</code></pre>
<h3 id="예제-3-모음과-자음-개수-세기">예제 3: 모음과 자음 개수 세기</h3>
<pre><code class="language-python">original = input(&#39;문자열을 입력하시오: &#39;)  # 예: &quot;Python&quot;
word = original.lower()
vowels = 0
consonants = 0

if len(original) &gt; 0 and original.isalpha():
    for char in word:
        if char in &#39;aeiou&#39;:
            vowels += 1
        else:
            consonants += 1

print(&quot;모음의 개수&quot;, vowels)
print(&quot;자음의 개수&quot;, consonants)
</code></pre>
<h3 id="예제-4-문자-유형별-개수-세기">예제 4: 문자 유형별 개수 세기</h3>
<pre><code class="language-python">statement = input(&quot;문자열을 입력하시오: &quot;)  # 예: &quot;Hello 123&quot;
alphas = 0
digits = 0
spaces = 0

for c in statement:
    if c.isalpha():
        alphas += 1
    if c.isdigit():
        digits += 1
    if c.isspace():
        spaces += 1

print(&quot;알파벳 개수=&quot;, alphas)
print(&quot;숫자 개수=&quot;, digits)
print(&quot;공백 개수=&quot;, spaces)
</code></pre>
<h3 id="예제-5-특수문자-제거-계좌번호-처리">예제 5: 특수문자 제거 (계좌번호 처리)</h3>
<pre><code class="language-python">account = input(&#39;계좌번호를 입력하시오: &#39;)  # 예: &quot;312-02-1234567&quot;
processed = &quot;&quot;

for c in account:
    if c != &quot;-&quot;:
        processed += c

print(processed)  # &quot;312021234567&quot;
</code></pre>
<h3 id="예제-6-회문palindrome-검사">예제 6: 회문(palindrome) 검사</h3>
<pre><code class="language-python">def check_pal(s):
    low = 0
    high = len(s) - 1

    while True:
        if low &gt; high:
            return True
        a = s[low]
        b = s[high]
        if a != b:
            return False
        low += 1
        high -= 1

s = input(&quot;문자열을 입력하시오: &quot;)  # 예: &quot;mom&quot; 또는 &quot;level&quot;
s = s.replace(&quot; &quot;, &quot;&quot;)  # 공백 제거
if check_pal(s):
    print(&quot;회문입니다.&quot;)
else:
    print(&quot;회문이 아닙니다.&quot;)
</code></pre>
<h2 id="8-중간고사-예상-문제-및-풀이">8. 중간고사 예상 문제 및 풀이</h2>
<h3 id="문제-1-문자열-조작-기본">문제 1: 문자열 조작 기본</h3>
<p>주어진 문자열의 모든 공백을 제거하고, 대문자로 변환한 후 출력하는 프로그램을 작성하시오.</p>
<pre><code class="language-python"># 답안
text = input(&quot;문자열을 입력하세요: &quot;)  # 예: &quot;Hello World Python&quot;
result = text.replace(&quot; &quot;, &quot;&quot;).upper()
print(result)  # &quot;HELLOWORLDPYTHON&quot;
</code></pre>
<h3 id="문제-2-이메일-주소-분석">문제 2: 이메일 주소 분석</h3>
<p>사용자로부터 이메일 주소를 입력받아 사용자 이름과 도메인을 분리하여 출력하는 프로그램을 작성하시오.</p>
<pre><code class="language-python"># 답안
email = input(&quot;이메일 주소를 입력하세요: &quot;)  # 예: &quot;user@example.com&quot;
username, domain = email.split(&#39;@&#39;)
print(&quot;사용자 이름:&quot;, username)
print(&quot;도메인:&quot;, domain)
</code></pre>
<h3 id="문제-3-비밀번호-유효성-검사">문제 3: 비밀번호 유효성 검사</h3>
<p>사용자로부터 비밀번호를 입력받아 다음 조건을 모두 만족하는지 검사하는 프로그램을 작성하시오.</p>
<ul>
<li>최소 8자 이상</li>
<li>최소 하나의 숫자 포함</li>
<li>최소 하나의 대문자 포함</li>
</ul>
<pre><code class="language-python"># 답안
password = input(&quot;비밀번호를 입력하세요: &quot;)

length_valid = len(password) &gt;= 8
digit_valid = False
upper_valid = False

for char in password:
    if char.isdigit():
        digit_valid = True
    if char.isupper():
        upper_valid = True

if length_valid and digit_valid and upper_valid:
    print(&quot;유효한 비밀번호입니다.&quot;)
else:
    print(&quot;유효하지 않은 비밀번호입니다.&quot;)
    if not length_valid:
        print(&quot;- 비밀번호는 최소 8자 이상이어야 합니다.&quot;)
    if not digit_valid:
        print(&quot;- 최소 하나의 숫자를 포함해야 합니다.&quot;)
    if not upper_valid:
        print(&quot;- 최소 하나의 대문자를 포함해야 합니다.&quot;)
</code></pre>
<h3 id="문제-4-문자열-통계">문제 4: 문자열 통계</h3>
<p>사용자로부터 문장을 입력받아 단어 수, 문자 수(공백 제외), 평균 단어 길이를 계산하는 프로그램을 작성하시오.</p>
<pre><code class="language-python"># 답안
sentence = input(&quot;문장을 입력하세요: &quot;)  # 예: &quot;Python is a great programming language&quot;

words = sentence.split()
word_count = len(words)
char_count = len(sentence.replace(&quot; &quot;, &quot;&quot;))
average_word_length = char_count / word_count if word_count &gt; 0 else 0

print(&quot;단어 수:&quot;, word_count)
print(&quot;문자 수(공백 제외):&quot;, char_count)
print(&quot;평균 단어 길이:&quot;, round(average_word_length, 2))
</code></pre>
<h3 id="문제-5-문자열-암호화">문제 5: 문자열 암호화</h3>
<p>사용자로부터 문자열을 입력받아 각 문자의 ASCII 코드값에 5를 더한 후, 해당 ASCII 코드값에 해당하는 문자로 변환하여 암호화하는 프로그램을 작성하시오.</p>
<pre><code class="language-python"># 답안
text = input(&quot;암호화할 문자열을 입력하세요: &quot;)  # 예: &quot;abc&quot;
encrypted = &quot;&quot;

for char in text:
    encrypted += chr(ord(char) + 5)

print(&quot;암호화된 문자열:&quot;, encrypted)  # &quot;fgh&quot;
</code></pre>
<h2 id="9-실전-대비-팁">9. 실전 대비 팁</h2>
<ol>
<li><strong>핵심 메소드 암기하기</strong><ul>
<li><code>upper()</code>, <code>lower()</code>, <code>strip()</code>, <code>split()</code>, <code>replace()</code> 등의 메소드 사용법을 숙지</li>
</ul>
</li>
<li><strong>인덱싱과 슬라이싱 연습하기</strong><ul>
<li>양수/음수 인덱스 모두 능숙하게 사용할 수 있어야 함</li>
<li>다양한 슬라이싱 범위에 대한 결과 예측 연습</li>
</ul>
</li>
<li><strong>자주 나오는 문제 유형 연습</strong><ul>
<li>회문 검사, 문자 개수 세기, 특정 문자 제거 등</li>
</ul>
</li>
<li><strong>문자열 포맷팅 방법 숙지</strong><ul>
<li><code>%s</code> 형식 지정자 사용법 이해</li>
</ul>
</li>
<li><strong>문자열 처리 알고리즘 이해하기</strong><ul>
<li>반복문과 조건문을 활용한 문자열 처리 패턴 연습</li>
</ul>
</li>
</ol>
<hr>
<p>확인 문제를 통해 개념 이해도를 체크해보세요!</p>
<h2 id="10-확인-문제">10. 확인 문제</h2>
<ol>
<li><p>다음 중 문자열에서 모든 공백을 제거하는 코드로 올바른 것은?</p>
<ul>
<li>A. <code>text.replace(&quot; &quot;)</code></li>
<li>B. <code>text.strip()</code></li>
<li>C. <code>text.replace(&quot; &quot;, &quot;&quot;)</code></li>
<li>D. <code>text.remove(&quot; &quot;)</code></li>
</ul>
</li>
<li><p>파이썬에서 문자열의 첫 번째 문자를 가리키는 인덱스는?</p>
<ul>
<li>A. 1</li>
<li>B. 0</li>
<li>C. -1</li>
<li>D. None</li>
</ul>
</li>
<li><p>다음 코드의 실행 결과는?</p>
<pre><code class="language-python"> s = &quot;Python Programming&quot;
 print(s[7:])
</code></pre>
<ul>
<li>A. &quot;Python&quot;</li>
<li>B. &quot;Programming&quot;</li>
<li>C. &quot;Py&quot;</li>
<li>D. &quot;thon Programming&quot;</li>
</ul>
</li>
<li><p>다음 중 문자열이 숫자로만 이루어져 있는지 확인하는 메소드는?</p>
<ul>
<li>A. <code>isalpha()</code></li>
<li>B. <code>isnumeric()</code></li>
<li>C. <code>isdigit()</code></li>
<li>D. <code>isnum()</code></li>
</ul>
</li>
<li><p>문자열 &quot;Hello&quot;를 3번 반복하는 코드는?</p>
<ul>
<li>A. <code>&quot;Hello&quot;.repeat(3)</code></li>
<li>B. <code>&quot;Hello&quot; * 3</code></li>
<li>C. <code>&quot;Hello&quot; + &quot;Hello&quot; + &quot;Hello&quot;</code></li>
<li>D. <code>&quot;Hello&quot;.multiply(3)</code></li>
</ul>
</li>
</ol>
<p><strong>답안: 1-C, 2-B, 3-B, 4-C, 5-B</strong></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter05+. __name__, 모듈 임포트]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter05.-name-%EB%AA%A8%EB%93%88-%EC%9E%84%ED%8F%AC%ED%8A%B8</link>
            <guid>https://velog.io/@lullaby_/PythonChapter05.-name-%EB%AA%A8%EB%93%88-%EC%9E%84%ED%8F%AC%ED%8A%B8</guid>
            <pubDate>Wed, 01 Oct 2025 01:18:48 GMT</pubDate>
            <description><![CDATA[<h2 id="1-핵심-개념-정리">1. 핵심 개념 정리</h2>
<h3 id="11-anaconda-개발-환경">1.1 Anaconda 개발 환경</h3>
<ul>
<li>Anaconda는 패키지 관리를 단순화하기 위한 파이썬 오픈 소스 배포판</li>
<li>패키지 관리 기능을 제공하여 라이브러리 설치 및 관리 용이</li>
</ul>
<h3 id="12-모듈과-__name__-변수">1.2 모듈과 <code>__name__</code> 변수</h3>
<ul>
<li>모듈: 함수, 변수, 클래스 등을 모아놓은 파이썬 파일</li>
<li><code>__name__</code> 변수: 현재 실행 중인 모듈의 이름을 저장하는 특수 변수<ul>
<li>직접 실행 시: <code>__main__</code></li>
<li>다른 모듈에서 임포트 시: 모듈 이름</li>
</ul>
</li>
</ul>
<h3 id="13-객체-속성과-메소드-탐색">1.3 객체 속성과 메소드 탐색</h3>
<ul>
<li><code>dir()</code> 함수: 객체가 가진 변수와 메소드를 보여주는 내장 함수</li>
<li>문자열 객체의 메소드 예: <code>upper()</code>, <code>lower()</code>, <code>split()</code> 등</li>
</ul>
<h3 id="14-모듈-임포트-방식">1.4 모듈 임포트 방식</h3>
<ol>
<li><code>import 모듈명</code>: 전체 모듈을 가져옴</li>
<li><code>from 모듈명 import 함수/변수</code>: 특정 함수나 변수만 가져옴</li>
<li><code>import 모듈명 as 별칭</code>: 별칭을 사용하여 모듈 임포트</li>
</ol>
<h2 id="2-코드-예제-분석">2. 코드 예제 분석</h2>
<h3 id="예제-1-기본-객체-탐색">예제 1: 기본 객체 탐색</h3>
<pre><code class="language-python">a = &quot;hi, python&quot;
print(a)
print(dir())  # 현재 네임스페이스의 변수/함수 목록
print(&quot;=&quot;*30)
print(dir(a))  # 문자열 객체의 메소드 목록
print(a.upper())  # 대문자 변환
</code></pre>
<h3 id="예제-2-__name__-변수-활용">예제 2: <code>__name__</code> 변수 활용</h3>
<pre><code class="language-python">def greetings(name):
    print(&#39;Hello,&#39;, name)

if __name__ == &#39;__main__&#39;:
    greetings(&quot;christina&quot;)
    greetings(&quot;daniel&quot;)
else:
    print(__name__)
</code></pre>
<h3 id="예제-3-나이-계산-함수와-모듈-활용">예제 3: 나이 계산 함수와 모듈 활용</h3>
<pre><code class="language-python"># test_04.py 모듈
print(&quot; &lt;&lt; test_04 모듈 &gt;&gt;&quot;)

def age():
    year = int(input(&quot;태어난 년도? &quot;))
    age = 2023-year
    return age

if __name__ == &#39;__main__&#39;:
    age = age()
    print(&quot;나이 : &quot;, age)
else:
    print(&quot;test_04 모듈이 임포트되었습니다.&quot;)
    print(&quot; test_04모듈 __name__ : &quot;, __name__)
    print(&quot; test_04모듈 age()함수에서 출력한 나이 : &quot;, age())
</code></pre>
<h3 id="예제-4-모듈-임포트-방식-비교">예제 4: 모듈 임포트 방식 비교</h3>
<pre><code class="language-python"># import 모듈명
import test_04
age = test_04.age()

# from 모듈명 import 함수
from test_04 import age
age = age()

# import 모듈명 as 별칭
import test_04 as t
age = t.age()
</code></pre>
<h2 id="3-예상-문제-및-답안">3. 예상 문제 및 답안</h2>
<h1 id="파이썬-중간고사-예상-문제-및-답안">파이썬 중간고사 예상 문제 및 답안</h1>
<h2 id="객관식-문제">객관식 문제</h2>
<h3 id="q1-anaconda의-주요-용도는-무엇인가">Q1. Anaconda의 주요 용도는 무엇인가?</h3>
<ol>
<li>파이썬 코드 컴파일</li>
<li>패키지 관리 및 라이브러리 설치</li>
<li>하드웨어 자원 최적화</li>
<li>웹 어플리케이션 배포</li>
</ol>
<p><strong>정답: 2</strong></p>
<h3 id="q2-다음-중-파이썬-모듈이-직접-실행될-때-__name__-변수의-값은">Q2. 다음 중 파이썬 모듈이 직접 실행될 때 <code>__name__</code> 변수의 값은?</h3>
<ol>
<li>&quot;module&quot;</li>
<li>&quot;python&quot;</li>
<li>&quot;<strong>main</strong>&quot;</li>
<li>모듈의 파일명</li>
</ol>
<p><strong>정답: 3</strong></p>
<h3 id="q3-다음-코드의-실행-결과로-올바른-것은">Q3. 다음 코드의 실행 결과로 올바른 것은?</h3>
<pre><code class="language-python">a = &quot;hello world&quot;
print(a.upper())
</code></pre>
<ol>
<li>&quot;Hello World&quot;</li>
<li>&quot;HELLO WORLD&quot;</li>
<li>&quot;hello world&quot;</li>
<li>오류 발생</li>
</ol>
<p><strong>정답: 2</strong></p>
<h3 id="q4-객체의-메소드와-속성을-확인하는-내장-함수는">Q4. 객체의 메소드와 속성을 확인하는 내장 함수는?</h3>
<ol>
<li><code>type()</code></li>
<li><code>list()</code></li>
<li><code>dir()</code></li>
<li><code>help()</code></li>
</ol>
<p><strong>정답: 3</strong></p>
<h3 id="q5-다른-모듈에서-함수를-가져올-때-사용하는-올바른-문법은">Q5. 다른 모듈에서 함수를 가져올 때 사용하는 올바른 문법은?</h3>
<ol>
<li><code>export function from module</code></li>
<li><code>include module.function</code></li>
<li><code>from module import function</code></li>
<li><code>require module.function</code></li>
</ol>
<p><strong>정답: 3</strong></p>
<h2 id="단답형-문제">단답형 문제</h2>
<h3 id="q6-printdir-명령어는-무엇을-보여주는가">Q6. <code>print(dir())</code> 명령어는 무엇을 보여주는가?</h3>
<p><strong>정답</strong>: 현재 네임스페이스에 있는 변수, 함수, 클래스 등의 이름 목록</p>
<h3 id="q7-파이썬에서-모듈의-별칭을-지정하는-문법은">Q7. 파이썬에서 모듈의 별칭을 지정하는 문법은?</h3>
<p><strong>정답</strong>: <code>import 모듈명 as 별칭</code></p>
<h3 id="q8-특정-문자열을-대문자로-변환하는-메소드는">Q8. 특정 문자열을 대문자로 변환하는 메소드는?</h3>
<p><strong>정답</strong>: <code>upper()</code></p>
<h3 id="q9-모듈이-다른-모듈에-임포트될-때-__name__-변수의-값은">Q9. 모듈이 다른 모듈에 임포트될 때 <code>__name__</code> 변수의 값은?</h3>
<p><strong>정답</strong>: 해당 모듈의 파일명(확장자 제외)</p>
<h3 id="q10-다음-코드에서-출력되는-값은">Q10. 다음 코드에서 출력되는 값은?</h3>
<pre><code class="language-python">print(&quot;python&quot;*3)
</code></pre>
<p><strong>정답</strong>: pythonpythonpython</p>
<h2 id="코드-작성-문제">코드 작성 문제</h2>
<h3 id="q11-두-개의-파이썬-파일을-만들어보세요">Q11. 두 개의 파이썬 파일을 만들어보세요:</h3>
<ol>
<li>&#39;calculator.py&#39; - 더하기, 빼기, 곱하기, 나누기 함수를 포함하며, 직접 실행 시 간단한 테스트를 수행</li>
<li>&#39;main.py&#39; - calculator 모듈을 임포트하여 사용자 입력으로 계산을 수행</li>
</ol>
<p><strong>답안 예시</strong>:</p>
<pre><code class="language-python"># calculator.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return &quot;Error: Division by zero&quot;
    return a / b

if __name__ == &#39;__main__&#39;:
    # 테스트 코드
    print(&quot;테스트 시작&quot;)
    print(f&quot;10 + 5 = {add(10, 5)}&quot;)
    print(f&quot;10 - 5 = {subtract(10, 5)}&quot;)
    print(f&quot;10 * 5 = {multiply(10, 5)}&quot;)
    print(f&quot;10 / 5 = {divide(10, 5)}&quot;)
    print(f&quot;10 / 0 = {divide(10, 0)}&quot;)
    print(&quot;테스트 종료&quot;)
</code></pre>
<pre><code class="language-python"># main.py
import calculator

print(&quot;간단한 계산기 프로그램&quot;)

while True:
    print(&quot;\n1: 더하기, 2: 빼기, 3: 곱하기, 4: 나누기, 0: 종료&quot;)
    choice = input(&quot;선택: &quot;)

    if choice == &#39;0&#39;:
        break

    if choice not in [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;]:
        print(&quot;잘못된 선택입니다.&quot;)
        continue

    a = float(input(&quot;첫 번째 숫자: &quot;))
    b = float(input(&quot;두 번째 숫자: &quot;))

    if choice == &#39;1&#39;:
        print(f&quot;결과: {calculator.add(a, b)}&quot;)
    elif choice == &#39;2&#39;:
        print(f&quot;결과: {calculator.subtract(a, b)}&quot;)
    elif choice == &#39;3&#39;:
        print(f&quot;결과: {calculator.multiply(a, b)}&quot;)
    else:
        print(f&quot;결과: {calculator.divide(a, b)}&quot;)

print(&quot;프로그램 종료&quot;)
</code></pre>
<h3 id="q12-다음-코드의-출력-결과를-예측하세요">Q12. 다음 코드의 출력 결과를 예측하세요:</h3>
<pre><code class="language-python">def test_function():
    print(&quot;함수 실행&quot;)
    return 42

if __name__ == &#39;__main__&#39;:
    value = test_function()
    print(f&quot;반환값: {value}&quot;)
</code></pre>
<p><strong>정답</strong>:</p>
<pre><code>함수 실행
반환값: 42
</code></pre><h3 id="q13-__name__-변수를-활용하여-직접-실행과-임포트-시-다르게-동작하는-모듈을-작성하세요">Q13. <code>__name__</code> 변수를 활용하여 직접 실행과 임포트 시 다르게 동작하는 모듈을 작성하세요.</h3>
<p><strong>답안 예시</strong>:</p>
<pre><code class="language-python"># my_module.py
def greet(name):
    return f&quot;안녕하세요, {name}님!&quot;

def calculate_age(birth_year):
    current_year = 2023
    return current_year - birth_year

if __name__ == &#39;__main__&#39;:
    # 직접 실행 시에만 아래 코드 실행
    print(&quot;모듈 테스트 모드&quot;)
    test_name = &quot;홍길동&quot;
    test_year = 2000
    print(f&quot;{test_name}에게 인사: {greet(test_name)}&quot;)
    print(f&quot;{test_name}의 나이: {calculate_age(test_year)}&quot;)
else:
    # 임포트 시에만 아래 코드 실행
    print(&quot;my_module이 임포트되었습니다&quot;)
</code></pre>
<h2 id="실전-문제">실전 문제</h2>
<h3 id="q14-다음-오류가-발생하는-이유를-설명하고-수정하세요">Q14. 다음 오류가 발생하는 이유를 설명하고 수정하세요:</h3>
<pre><code class="language-python">import my_functions

result = my_functions.square(5)
print(result)
</code></pre>
<p>오류: <code>AttributeError: module &#39;my_functions&#39; has no attribute &#39;square&#39;</code></p>
<p><strong>정답</strong>:
<code>my_functions</code> 모듈에 <code>square</code> 함수가 정의되어 있지 않습니다. 모듈에 해당 함수를 정의하거나, 올바른 함수 이름을 사용해야 합니다.</p>
<p>수정 예시:</p>
<pre><code class="language-python"># my_functions.py 파일에 다음 함수 추가
def square(x):
    return x * x
</code></pre>
<h3 id="q15-다음-코드의-문제점을-찾고-수정하세요">Q15. 다음 코드의 문제점을 찾고 수정하세요:</h3>
<pre><code class="language-python">from math import *

def calculate_area(radius):
    return pi * radius ** 2

if __name__ = &#39;__main__&#39;:
    radius = 5
    area = calculate_area(radius)
    print(f&quot;반지름이 {radius}인 원의 면적: {area}&quot;)
</code></pre>
<p><strong>정답</strong>:
두 가지 문제가 있습니다:</p>
<ol>
<li><code>if __name__ = &#39;__main__&#39;:</code> 부분에서 비교 연산자 <code>==</code>가 아닌 할당 연산자 <code>=</code>를 사용했습니다.</li>
<li><code>from math import *</code>은 네임스페이스 오염을 일으킬 수 있어 권장되지 않습니다.</li>
</ol>
<p>수정 코드:</p>
<pre><code class="language-python">from math import pi  # 필요한 함수만 임포트

def calculate_area(radius):
    return pi * radius ** 2

if __name__ == &#39;__main__&#39;:  # == 사용
    radius = 5
    area = calculate_area(radius)
    print(f&quot;반지름이 {radius}인 원의 면적: {area}&quot;)
</code></pre>
<h2 id="4-실전-대비-추가-팁">4. 실전 대비 추가 팁</h2>
<h3 id="모듈-시스템-이해하기">모듈 시스템 이해하기</h3>
<ul>
<li>모듈은 파이썬 코드를 논리적으로 조직화하는 기본 단위</li>
<li>적절한 모듈 구조는 코드 재사용성과 유지보수성을 높임</li>
<li><code>__name__</code> 변수를 활용한 모듈 테스트 코드 패턴은 실무에서 매우 중요</li>
</ul>
<h3 id="ide-능숙하게-사용하기">IDE 능숙하게 사용하기</h3>
<ul>
<li>코드 자동완성, 디버깅 도구 사용법 숙지</li>
<li>PyCharm의 단축키 익히기 (예: Alt + Shift + E로 한 줄씩 실행)</li>
<li>가상환경 관리와 패키지 설치 방법 익히기</li>
</ul>
<h3 id="문자열-메소드-숙달하기">문자열 메소드 숙달하기</h3>
<ul>
<li><code>upper()</code>, <code>lower()</code>, <code>strip()</code>, <code>split()</code> 등의 주요 메소드 사용법 익히기</li>
<li>문자열 포맷팅 방식 (f-string, format 메소드) 능숙하게 사용하기</li>
</ul>
<h3 id="모듈-임포트-방식별-장단점-이해하기">모듈 임포트 방식별 장단점 이해하기</h3>
<ul>
<li><code>import module</code><ul>
<li>장점: 네임스페이스 충돌 방지</li>
<li>단점: 모듈명을 항상 명시해야 함</li>
</ul>
</li>
<li><code>from module import function</code><ul>
<li>장점: 함수 직접 호출 가능</li>
<li>단점: 이름 충돌 가능성</li>
</ul>
</li>
<li><code>import module as alias</code><ul>
<li>장점: 긴 모듈명 축약 가능</li>
<li>사용법: 가독성을 고려한 적절한 별칭 사용</li>
</ul>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter05. 루프와 반복문(예제다수)]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter05.-%EB%A3%A8%ED%94%84%EC%99%80-%EB%B0%98%EB%B3%B5%EB%AC%B8%EC%98%88%EC%A0%9C%EB%8B%A4%EC%88%98</link>
            <guid>https://velog.io/@lullaby_/PythonChapter05.-%EB%A3%A8%ED%94%84%EC%99%80-%EB%B0%98%EB%B3%B5%EB%AC%B8%EC%98%88%EC%A0%9C%EB%8B%A4%EC%88%98</guid>
            <pubDate>Wed, 01 Oct 2025 01:16:55 GMT</pubDate>
            <description><![CDATA[<h2 id="1-핵심-개념-루프와-반복문">1. 핵심 개념: 루프와 반복문</h2>
<h3 id="11-while-반복문">1.1 while 반복문</h3>
<p><strong>기본 구조:</strong></p>
<pre><code class="language-python">while 조건:
    # 반복할 코드
    # 조건이 참인 동안 계속 실행됨
</code></pre>
<p><strong>주요 특징:</strong></p>
<ul>
<li>조건이 참인 동안 계속 실행</li>
<li>무한 루프 방지를 위해 반복 조건이 언젠가는 거짓이 되도록 설계해야 함</li>
<li>변수 초기화가 루프 전에 필요함</li>
</ul>
<h3 id="12-for-반복문">1.2 for 반복문</h3>
<p><strong>기본 구조:</strong></p>
<pre><code class="language-python">for 변수 in 범위/시퀀스:
    # 반복할 코드
</code></pre>
<p><strong>주요 특징:</strong></p>
<ul>
<li><code>range()</code> 함수와 많이 사용됨: <code>range(시작, 끝, 스텝)</code></li>
<li>리스트, 문자열 등 순회 가능한 객체에 대해 반복 수행</li>
<li>횟수가 정해진 반복에 적합</li>
</ul>
<h3 id="13-반복문-제어-명령어">1.3 반복문 제어 명령어</h3>
<ul>
<li><strong>break</strong>: 반복문을 완전히 종료</li>
<li><strong>센티널 값</strong>: 특정 값이 입력되면 반복문을 종료하는 방식<ul>
<li><strong>continue</strong>: 현재 반복을 중단하고 다음 반복으로 이동</li>
</ul>
</li>
</ul>
<h3 id="14-중첩-반복문">1.4 중첩 반복문</h3>
<p><strong>기본 구조:</strong></p>
<pre><code class="language-python">for i in range():
    for j in range():
        # 코드 실행
</code></pre>
<p><strong>주요 특징:</strong></p>
<ul>
<li>반복문 안에 또 다른 반복문이 있는 구조</li>
<li>행렬, 그리드 작업, 복잡한 패턴 생성에 유용</li>
<li>실행 시간이 급격히 증가할 수 있으므로 효율성 고려 필요</li>
</ul>
<h2 id="2-주요-예제-분석">2. 주요 예제 분석</h2>
<h3 id="21-구구단-출력-while-문">2.1 구구단 출력 (while 문)</h3>
<pre><code class="language-python">print(&quot;구구단 출력&quot;)
print(&quot;-&quot;*30)
dan = int(input(&quot;몇 단을 출력할까요 ? &quot;))
i = 1
while i &lt;= 9:
    print(&quot;%d * %d = %d&quot; %(dan, i, dan*i))
    i = i + 1
</code></pre>
<p><strong>핵심 포인트:</strong></p>
<ul>
<li>변수 초기화: <code>i = 1</code></li>
<li>반복 조건: <code>i &lt;= 9</code></li>
<li>변수 증가: <code>i = i + 1</code></li>
</ul>
<h3 id="22-배수의-합-계산">2.2 배수의 합 계산</h3>
<pre><code class="language-python">sum = 0
number = 1
while number &lt;= 100:
    if number % 3 == 0:
        sum = sum + number
    number = number + 1
print(&quot;1부터 100사이의 모든 3의 배수의 합은 %d입니다.&quot; % sum)
</code></pre>
<p><strong>핵심 포인트:</strong></p>
<ul>
<li>누적 합계 변수: <code>sum = 0</code></li>
<li>조건부 누적: <code>if number % 3 == 0</code></li>
<li>범위 지정: <code>while number &lt;= 100</code></li>
</ul>
<h3 id="23-자리수의-합-계산">2.3 자리수의 합 계산</h3>
<pre><code class="language-python">number = int(input(&quot;자리수의 합을 계산하기 위한 값을 입력하시오 : &quot;))
sum = 0
while number &gt; 0:
    digit = number % 10
    sum = sum + digit
    number = number // 10
print(&quot;자리수의 합은 %d입니다.&quot; % sum)
</code></pre>
<p><strong>핵심 포인트!!!!!!!!!!!!!!!:</strong></p>
<ul>
<li>1의 자리 추출: <code>digit = number % 10</code></li>
<li>자릿수 이동: <code>number = number // 10</code></li>
<li>종료 조건: <code>number &gt; 0</code> (모든 자릿수 처리 완료)</li>
</ul>
<h3 id="24-센티널을-이용한-성적-평균-계산">2.4 센티널을 이용한 성적 평균 계산</h3>
<pre><code class="language-python">n = 0
sum = 0
score = 0
print(&quot;종료하려면 음수를 입력하시오&quot;)
while score &gt;= 0:
    score = int(input(&quot;성적을 입력하시오: &quot;))
    if score &gt; 0:
        sum = sum + score
        n = n + 1
if n &gt; 0:
    average = sum / n
    print(&quot;성적의 평균은 %f입니다.&quot; % average)
</code></pre>
<p><strong>핵심 포인트:</strong></p>
<ul>
<li>센티널 값: 음수 입력 시 종료</li>
<li>유효한 데이터만 처리: <code>if score &gt; 0</code></li>
<li>평균 계산 전 분모 검사: <code>if n &gt; 0</code></li>
</ul>
<h3 id="25-숫자-맞추기-게임">2.5 숫자 맞추기 게임</h3>
<pre><code class="language-python">import random
tries = 0
number = random.randint(1, 100)
print(&quot;1부터 100사이의 숫자를 맞추시오&quot;)
while tries &lt; 10:
    guess = int(input(&quot;숫자를 입력하시오: &quot;))
    tries = tries + 1
    if guess &lt; number:
        print(&quot;컴퓨터가 생각하는 숫자보다 더 작음!&quot;)
    elif guess &gt; number:
        print(&quot;컴퓨터가 생각하는 숫자보다 더 큼!&quot;)
    else:
        break
if guess == number:
    print(&quot;축하합니다.정답입니다.시도횟수=&quot;, tries)
else:
    print(&quot;정답은 &quot;, number)
</code></pre>
<p><strong>핵심 포인트:</strong></p>
<ul>
<li>무작위 수 생성: <code>random.randint(1, 100)</code></li>
<li>시도 횟수 제한: <code>tries &lt; 10</code></li>
<li>break 사용: 정답을 맞췄을 때 반복문 탈출</li>
</ul>
<h3 id="26-가위-바위-보-게임">2.6 가위 바위 보 게임</h3>
<pre><code class="language-python">from random import randint
def game(player):
    while True:
        player = input(&quot;scissors, rock, paper중에서 하나를 입력하고,게임을 끝내려면 q를 입력하세요: &quot;)
        if player == &quot;q&quot;:
            return
        elif player == &quot;scissors&quot;:
            playerNum = 0
        elif player == &quot;rock&quot;:
            playerNum = 1
        elif player == &quot;paper&quot;:
            playerNum = 2
        else:
            continue
        list = [&quot;scissors&quot;, &quot;rock&quot;, &quot;paper&quot;]
        comNum = randint(0,2)
        print(&quot;● user :&quot;, player, &quot;● computer :&quot;, list[comNum])
        if (playerNum-comNum==0):
            print(&quot;user and computer are in the same.&quot;)
        elif (playerNum-comNum==-2 or playerNum-comNum==1):
            print(&quot;user win !!&quot;)
        else:
            print(&quot;computer win !!&quot;)

player = input(&quot;게임을 시작하려면 s를 입력하세요: &quot;)
if player ==&quot;s&quot;:
    print(&quot;게임이 시작되었습니다.&quot;)
    game(player)
</code></pre>
<p><strong>핵심 포인트:</strong></p>
<ul>
<li>continue 사용: 잘못된 입력 시 재입력 요청</li>
<li>함수 내부의 무한 루프: <code>while True</code></li>
<li>간단한 승패 결정 로직: <code>playerNum-comNum</code> 값 비교</li>
</ul>
<h3 id="27-중첩-반복문을-이용한-패턴-출력">2.7 중첩 반복문을 이용한 패턴 출력</h3>
<pre><code class="language-python">for y in range(5):
    for x in range(10):
        print(&quot;* &quot;, end=&quot;&quot;)
    print()
</code></pre>
<p><strong>핵심 포인트:</strong></p>
<ul>
<li>외부 루프: 행 반복 (<code>y</code>)</li>
<li>내부 루프: 열 반복 (<code>x</code>)</li>
<li><code>end=&quot;&quot;</code> 파라미터로 줄바꿈 제어</li>
</ul>
<h3 id="28-피타고라스-직각삼각형-찾기">2.8 피타고라스 직각삼각형 찾기</h3>
<pre><code class="language-python">for a in range(1, 101, 1):
    for b in range(a, 101, 1):
        for c in range(b, 101, 1):
            if((a*a+b*b)==c*c):
                print(a, b, c)
</code></pre>
<p><strong>핵심 포인트:</strong></p>
<ul>
<li>3중 중첩 반복문 사용</li>
<li>효율성 향상: <code>b</code>는 <code>a</code>부터, <code>c</code>는 <code>b</code>부터 시작</li>
<li>조건 검사: 피타고라스 정리 <code>a²+b²=c²</code></li>
</ul>
<h2 id="3-예상-문제-및-풀이">3. 예상 문제 및 풀이</h2>
<h3 id="문제-1-while-루프-기초">문제 1: while 루프 기초</h3>
<p><strong>문제:</strong> 1부터 사용자가 입력한 수까지의 합을 계산하는 프로그램을 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">n = int(input(&quot;숫자를 입력하세요: &quot;))
sum = 0
i = 1 #while은 초깃값 뺴먹지말기!!!!!!

while i &lt;= n:
    sum += i
    i += 1

print(f&quot;1부터 {n}까지의 합은 {sum}입니다.&quot;)
</code></pre>
<h3 id="문제-2-for-루프와-range-함수">문제 2: for 루프와 range 함수</h3>
<p><strong>문제:</strong> range 함수를 사용하여 10부터 1까지 역순으로 출력하는 프로그램을 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">for i in range(10, 0, -1):
    print(i, end=&quot; &quot;)
print()  # 줄바꿈
</code></pre>
<h3 id="문제-3-break와-continue-활용">문제 3: break와 continue 활용</h3>
<p><strong>문제:</strong> 1부터 100까지 숫자 중 7의 배수이거나 3의 배수인 경우만 출력하되, 합이 200을 초과하면 중단하는 프로그램을 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">sum = 0
for num in range(1, 101):
    if num % 7 == 0 or num % 3 == 0:
        print(num, end=&quot; &quot;)
        sum += num
        if sum &gt; 200:
            print(&quot;\n합이 200을 초과했습니다. 현재 합:&quot;, sum)
            break
    else:
        continue
</code></pre>
<h3 id="문제-4-자리수-계산">문제 4: 자리수 계산</h3>
<p><strong>문제:</strong> </p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">number = int(input(&quot;정수를 입력하세요: &quot;))
original = number
count = 0

while number &gt; 0:
    number = number // 10
    count += 1

print(f&quot;{original}은(는) {count}자리 수입니다.&quot;)
</code></pre>
<h3 id="문제-5-중첩-반복문-패턴">문제 5: 중첩 반복문 패턴</h3>
<p><strong>문제:</strong> 다음과 같은 패턴을 출력하는 프로그램을 작성하시오.</p>
<pre><code>*
**
***
****
*****
</code></pre><p><strong>풀이:</strong></p>
<pre><code class="language-python">rows = 5
for i in range(1, rows + 1):
    for j in range(i):
        print(&quot;*&quot;, end=&quot;&quot;)
    print()
</code></pre>
<h3 id="문제-6-소수-찾기">문제 6: 소수 찾기</h3>
<p><strong>문제:</strong> 2부터 100까지의 모든 소수를 찾아 출력하는 프로그램을 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">for num in range(2, 101):  # 2부터 100까지의 모든 숫자(num)를 확인
    is_prime = True  # 소수 여부를 저장하는 변수 (기본적으로 True로 설정)

    for i in range(2, int(num**0.5) + 1):  # 2부터 num의 제곱근까지 반복
        if num % i == 0:  # 나누어 떨어지는 수가 있으면
            is_prime = False  # 소수가 아님
            break  # 더 확인할 필요 없으므로 반복문 종료

    if is_prime:  # 소수라면 출력
        print(num, end=&quot; &quot;)  # 한 줄로 출력하기 위해 end=&quot; &quot; 추가3</code></pre>
<h3 id="문제-7-센티널-값을-활용한-데이터-입력">문제 7: 센티널 값을 활용한 데이터 입력</h3>
<p><strong>문제:</strong> 사용자로부터 숫자를 입력받아 합계를 계산하되, 0이 입력되면 입력을 중단하고 지금까지의 합계와 평균을 출력하는 프로그램을 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">sum = 0
count = 0
print(&quot;숫자들을 입력하세요 (종료는 0):&quot;)

while True:
    num = float(input(&quot;숫자: &quot;))
    if num == 0:
        break
    sum += num
    count += 1

if count &gt; 0:
    print(f&quot;합계: {sum}&quot;)
    print(f&quot;평균: {sum / count}&quot;)
else:
    print(&quot;입력된 숫자가 없습니다.&quot;)
</code></pre>
<pre><code class="language-python">&#39;&#39;&#39;### 문### 문제 7: 센티널 값을 활용한 데이터 입력

**문제:** 사용자로부터 숫자를 입력받아 합계를 계산하되,
0이 입력되면 입력을 중단하고 지금까지의
합계와 평균을 출력하는 프로그램을 작성하시오.&#39;&#39;&#39;
sum=0
count=0
# 걍 냅다 print처넣기
&#39;&#39;&#39;알고리즘
1. while True처넣기
2. 숫자입력
3. 만약 입력된숫자가 0임: 멈춰씨발!
4. 아님:(계속진행됨): num추가, 카운트 +1
5. 이 다음은 break 당한 경우밖에 없으므로 만약 카운트&gt;0: 합계평균출력
아님: 입력된숫자가없음을어필!)&#39;&#39;&#39;
print(&quot;숫자들을 입력하세요(종료는 0)&quot;)
while True:
    num = float(input(&quot;숫자?: &quot;))
    if num == 0:
        break
    sum += num
    count += 1

if count&gt;0:
    print(f&quot;지금까지 입력된 숫자의 합계는: {sum}, 평균은 {sum/count}&quot;)
else:
    print(&quot;입력된 숫자가 없습니다.&quot;)
</code></pre>
<h3 id="문제-8-난수-생성과-반복문">문제 8: 난수 생성과 반복문</h3>
<p><strong>문제:</strong> 주사위를 100번 던져서 각 숫자(1~6)가 나온 횟수를 세는 프로그램을 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">import random

counts = [0, 0, 0, 0, 0, 0]  # 인덱스 0은 사용하지 않음

for i in range(100):
    dice = random.randint(1, 6)
    counts[dice-1] += 1

for i in range(6):
    print(f&quot;숫자 {i+1}: {counts[i]}번&quot;)
</code></pre>
<pre><code class="language-python">#내가한거
&#39;&#39;&#39;알고리즘
1. 랜덤임포트
2. 카운트리스트 준비
3. 100번굴려
4. 주사위수 = r.randint 지정해둠
5. 카운트[주사위수-1] += 1
개빡세네 시발
내가잘한점: 리스트[숫자] += 1 이거어케생각햇대 ㅎ&#39;&#39;&#39;
import random as r

counts = [0, 0, 0, 0, 0, 0]
for i in range(100):
    num = r.randint(1,6)
    counts[num-1] += 1
print(counts[0], counts[1], counts[2], counts[3], counts[4], counts[5])
</code></pre>
<h3 id="문제-9-중첩-루프와-조건문개잘햇죠ㅋㅋ">문제 9: 중첩 루프와 조건문(개잘햇죠?ㅋㅋ)</h3>
<p><strong>문제:</strong> 구구단 중 짝수 단(2, 4, 6, 8단)만 출력하는 프로그램을 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">for dan in range(2, 10, 2):
    print(f&quot;\n== {dan}단 ==&quot;)
    for i in range(1, 10):
        print(f&quot;{dan} × {i} = {dan * i}&quot;)
</code></pre>
<h3 id="문제-10-실전-응용-문제">문제 10: 실전 응용 문제</h3>
<p><strong>문제:</strong> 사용자로부터 양의 정수 n을 입력받아, 피보나치 수열의 첫 n개 항을 출력하는 프로그램을 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-python">n = int(input(&quot;출력할 피보나치 수열의 항 개수: &quot;))

a, b = 0, 1 #초깃값지정해두기!! 피보나치수열=1,1,2,3...이딴식으로전개됨
count = 0

while count &lt; n:
    print(a, end=&quot; &quot;) #앞두자리수의합&gt;다음b가되므로 a만출력: ㅇㅋ
    a, b = b, a + b
    count += 1
</code></pre>
<h2 id="4-실전-대비-연습-문제">4. 실전 대비 연습 문제</h2>
<h1 id="python-반복문-실전-대비-연습-문제">Python 반복문 실전 대비 연습 문제</h1>
<h2 id="기초-연습-문제">기초 연습 문제</h2>
<h3 id="문제-1-팩토리얼-계산">문제 1: 팩토리얼 계산</h3>
<p>n!을 계산하는 프로그램을 작성하시오. (n은 사용자 입력)</p>
<h3 id="문제-2-구구단">문제 2: 구구단</h3>
<p>사용자가 입력한 단 ~ 9단까지 구구단을 출력하는 프로그램을 작성하시오.</p>
<h3 id="문제-3-약수-찾기">문제 3: 약수 찾기</h3>
<p>사용자가 입력한 숫자의 모든 약수를 찾아 출력하는 프로그램을 작성하시오.</p>
<h2 id="중급-연습-문제">중급 연습 문제</h2>
<h3 id="문제-4-완전수-찾기">문제 4: 완전수 찾기</h3>
<p>1부터 1000까지의 수 중에서 완전수를 모두 찾아 출력하시오.
(완전수는 자기 자신을 제외한 약수의 합이 자기 자신과 같은 수)</p>
<pre><code class="language-python">#1부터 1000까지의 수 중에서 완전수를 모두 찾아 출력하시오.
#(완전수는 자기 자신을 제외한 약수의 합이 자기 자신과 같은 수) 

for i in range(1,1001):
    sum = 0
    for n in range(1, i):
        if i%n ==0:
            sum += n
        else:
            continue
    if sum == i:
        print(i, end=&quot; &quot;)</code></pre>
<h3 id="문제-5-암스트롱-수-찾기">문제 5: 암스트롱 수 찾기</h3>
<p>100부터 999까지의 암스트롱 수를 모두 찾아 출력하시오.
(각 자릿수의 세제곱의 합이 원래 수와 같은 수)</p>
<pre><code class="language-python">### 문제 5: 암스트롱 수 찾기

#100부터 999까지의 암스트롱 수를 모두 찾아 출력하시오.
#(각 자릿수의 세제곱의 합이 원래 수와 같은 수)
a=0
b=0
c=0
for i in range(100,1000):
    a=i//100 #백의자리수
    b=(i-a*100)//10 #십의자리수
    c=i%10
    if (a**3 + b**3 + c**3 == i):
        print(i)
</code></pre>
<h3 id="문제-6-별-패턴-출력">문제 6: 별 패턴 출력</h3>
<p>다음과 같은 패턴을 출력하시오.</p>
<pre><code>    *
   ***
  *****
 *******
*********
</code></pre><pre><code class="language-python">for i in range(1,6):
    print(&quot; &quot;*(6-i), &quot;*&quot;*(2*i-1)) 우 하 하</code></pre>
<h2 id="고급-연습-문제">고급 연습 문제</h2>
<h3 id="문제-7-콜라츠-추측">문제 7: 콜라츠 추측</h3>
<p>사용자가 입력한 양의 정수 n에 대해 콜라츠 추측을 적용하여 1이 될 때까지의 과정과 단계 수를 출력하시오.</p>
<ul>
<li>n이 짝수면 2로 나눔</li>
<li>n이 홀수면 3을 곱하고 1을 더함</li>
<li>위 과정을 n이 1이 될 때까지 반복</li>
<li></li>
</ul>
<pre><code class="language-python">### 문제 7: 콜라츠 추측

#사용자가 입력한 양의 정수 n에 대해
#콜라츠 추측을 적용하여 1이 될 때까지의 과정과 단계 수를 출력하시오.

#- n이 짝수면 2로 나눔
#- n이 홀수면 3을 곱하고 1을 더함
#- 위 과정을 n이 1이 될 때까지 반복

num = int(input(&quot;정수를 입력하시오: &quot;))
while num != 1:
    if num%2 == 0:
        num //= 2
        print(&quot;num//2=&quot;, num)
    elif num%2 == 1:
        num = num*3 + 1
        print(&quot;num*3-1=&quot;,num)
</code></pre>
<h3 id="문제-8-최대공약수와-최소공배수">문제 8: 최대공약수와 최소공배수</h3>
<p>두 수를 입력받아 최대공약수와 최소공배수를 계산하는 프로그램을 작성하시오.</p>
<h3 id="문제-9-로또-번호-생성기">문제 9: 로또 번호 생성기</h3>
<p>1부터 45까지의 숫자 중에서 중복되지 않는 6개의 숫자를 무작위로 선택하여 출력하는 로또 번호 생성기를 작성하시오.</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter04. for, while, turtle]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter04.-for-while-turtle</link>
            <guid>https://velog.io/@lullaby_/PythonChapter04.-for-while-turtle</guid>
            <pubDate>Wed, 01 Oct 2025 01:15:30 GMT</pubDate>
            <description><![CDATA[<h2 id="1-for-반복문-for-loops">1. For 반복문 (For Loops)</h2>
<h3 id="주요-개념">주요 개념</h3>
<ul>
<li>시퀀스(문자열, 리스트 등)를 순회할 때 사용</li>
<li><code>range()</code> 함수를 활용한 반복</li>
<li>다양한 반복 패턴 구현 가능</li>
</ul>
<h3 id="예제-코드">예제 코드</h3>
<pre><code class="language-python"># 기본 for 반복문 예시
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4 출력

# 문자열 순회
for char in &quot;python&quot;:
    print(char)  # p, y, t, h, o, n 각각 출력

# 1부터 10까지의 합 계산
sum = 0
for i in range(1, 11):
    sum += i
print(f&quot;1부터 10까지의 합: {sum}&quot;)  # 55
</code></pre>
<h3 id="주요-range-함수-사용법">주요 <code>range()</code> 함수 사용법</h3>
<ul>
<li><code>range(stop)</code>: 0부터 stop-1까지</li>
<li><code>range(start, stop)</code>: start부터 stop-1까지</li>
<li><code>range(start, stop, step)</code>: start부터 stop-1까지 step 간격으로</li>
</ul>
<h2 id="2-while-반복문-while-loops">2. While 반복문 (While Loops)</h2>
<h3 id="주요-개념-1">주요 개념</h3>
<ul>
<li>조건이 참인 동안 반복 수행</li>
<li>반복 횟수를 미리 알 수 없는 경우 유용</li>
<li>무한 루프 주의</li>
</ul>
<h3 id="예제-코드-1">예제 코드</h3>
<pre><code class="language-python"># 기본 while 반복문
i = 0
while i &lt; 5:
    print(i)
    i += 1  # 0, 1, 2, 3, 4 출력

# 팩토리얼 계산
factorial = 1
n = 10
i = 1
while i &lt;= n:
    factorial *= i
    i += 1
print(f&quot;{n}! = {factorial}&quot;)  # 3,628,800
</code></pre>
<h2 id="3-반복문-활용-예시---turtle-그래픽">3. 반복문 활용 예시 - Turtle 그래픽</h2>
<h3 id="다각형-그리기">다각형 그리기</h3>
<pre><code class="language-python">import turtle

# 육각형 그리기
polygon = turtle.Turtle()
num_sides = 6
side_length = 70
angle = 360.0 / num_sides

for i in range(num_sides):
    polygon.forward(side_length)
    polygon.right(angle)
</code></pre>
<h3 id="sin-곡선-그리기">Sin 곡선 그리기</h3>
<pre><code class="language-python">import math
import turtle

t = turtle.Turtle()
t.speed(&#39;fastest&#39;)

for degree in range(360):
    y = math.sin(math.radians(degree))
    scaledX = degree
    scaledY = y * 100
    t.goto(scaledX, scaledY)
</code></pre>
<h2 id="4-중간고사-예상-문제">4. 중간고사 예상 문제</h2>
<h3 id="이론-문제">이론 문제</h3>
<ol>
<li><p><code>for</code>와 <code>while</code> 반복문의 차이점은 무엇인가? </p>
<ul>
<li><p>답</p>
<h3 id="for-반복문"><code>for</code> 반복문</h3>
<ul>
<li><p>미리 정해진 시퀀스나 횟수를 반복할 때 사용</p>
</li>
<li><p>반복 횟수를 알고 있는 경우에 적합</p>
</li>
<li><p>주로 리스트, 문자열, <code>range()</code> 등과 함께 사용</p>
</li>
<li><p>반복 횟수가 명확하고 정해진 범위 내에서 반복할 때 효율적</p>
<h3 id="while-반복문"><code>while</code> 반복문</h3>
</li>
<li><p>조건이 참인 동안 계속 반복</p>
</li>
<li><p>반복 횟수를 미리 알 수 없는 경우에 적합</p>
</li>
<li><p>특정 조건이 만족될 때까지 반복</p>
</li>
<li><p>조건 검사를 먼저 수행하고 반복 여부 결정</p>
</li>
<li><p>무한 루프 가능성이 있어 주의 필요</p>
<h3 id="주요-차이점">주요 차이점</h3>
</li>
<li><p>반복 제어 방식:</p>
<ul>
<li><code>for</code>: 정해진 범위나 시퀀스 순회</li>
<li><code>while</code>: 조건 기반 반복</li>
</ul>
</li>
<li><p>사용 상황:</p>
<ul>
<li><code>for</code>: 알려진 반복 횟수나 시퀀스 순회</li>
<li><code>while</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><p><code>range(5, 10, 2)</code>는 어떤 값을 생성하는가?</p>
<ul>
<li><p>답</p>
<h3 id="정답">정답</h3>
<ul>
<li><p><code>[5, 7, 9]</code>를 생성</p>
</li>
<li><p>시작값: 5</p>
</li>
<li><p>끝값: 10 이전까지 (10 제외)</p>
</li>
<li><p>증가 간격: 2</p>
<h3 id="상세-설명">상세 설명</h3>
</li>
<li><p>첫 번째 인자 <code>5</code>: 시작값</p>
</li>
<li><p>두 번째 인자 <code>10</code>: 종료값 (이 값은 포함되지 않음)</p>
</li>
<li><p>세 번째 인자 <code>2</code>: 각 단계별 증가값</p>
</li>
<li><p>5부터 시작해서 2씩 증가하며 10 미만까지 생성</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p>반복문에서 <code>break</code>와 <code>continue</code>의 역할은 무엇인가? </p>
<ul>
<li><p>답</p>
<h3 id="break"><code>break</code></h3>
<ul>
<li><p>반복문을 즉시 종료하고 반복문 밖으로 탈출</p>
</li>
<li><p>특정 조건에서 반복을 완전히 중단할 때 사용</p>
</li>
<li><p>반복문의 모든 후속 반복을 건너뜀</p>
<h3 id="예시">예시</h3>
<pre><code class="language-python">python
복사
for i in range(10):
  if i == 5:
      break  # 5에서 반복문 완전 종료
  print(i)  # 0, 1, 2, 3, 4만 출력
</code></pre>
<h3 id="continue"><code>continue</code></h3>
</li>
<li><p>현재 반복의 나머지 코드를 건너뛰고 다음 반복으로 진행</p>
</li>
<li><p>특정 조건에서 해당 반복만 건너뛰고 싶을 때 사용</p>
</li>
<li><p>반복문 자체는 계속 진행</p>
<h3 id="예시-1">예시</h3>
<pre><code class="language-python">python
복사
for i in range(10):
  if i % 2 == 0:
      continue  # 짝수일 경우 건너뜀
  print(i)  # 1, 3, 5, 7, 9만 출력
</code></pre>
<h3 id="주요-차이점-1">주요 차이점</h3>
</li>
<li><p><code>break</code>: 반복문 전체 종료</p>
</li>
<li><p><code>continue</code>: 현재 반복만 건너뛰고 다음 반복 진행</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<h3 id="코딩-문제">코딩 문제</h3>
<ol>
<li>1부터 100까지의 짝수의 합을 계산하는 프로그램을 작성하시오.</li>
<li>사용자로부터 입력받은 정수의 팩토리얼을 계산하는 프로그램을 작성하시오.</li>
<li>Turtle 그래픽을 사용하여 8개의 원을 그리는 프로그램을 작성하시오.</li>
</ol>
<h3 id="예시-솔루션">예시 솔루션</h3>
<pre><code class="language-python"># 1. 1부터 100까지 짝수의 합
even_sum = 0
for i in range(2, 101, 2):
    even_sum += i
print(f&quot;짝수의 합: {even_sum}&quot;)

# 2. 사용자 입력 팩토리얼 계산
n = int(input(&quot;정수를 입력하세요: &quot;))
factorial = 1
for i in range(1, n+1):
    factorial *= i
print(f&quot;{n}! = {factorial}&quot;)

# 3. 8개의 원 그리기
import turtle
t = turtle.Turtle()
for i in range(8):
    t.circle(100)
    t.right(360/8)
</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter03. 함수, 함수의 변수작동방식(call by value, call by reference), 반복문]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter03.-%ED%95%A8%EC%88%98-%ED%95%A8%EC%88%98%EC%9D%98-%EB%B3%80%EC%88%98%EC%9E%91%EB%8F%99%EB%B0%A9%EC%8B%9Dcall-by-value-call-by-reference-%EB%B0%98%EB%B3%B5%EB%AC%B8-dncx016z</link>
            <guid>https://velog.io/@lullaby_/PythonChapter03.-%ED%95%A8%EC%88%98-%ED%95%A8%EC%88%98%EC%9D%98-%EB%B3%80%EC%88%98%EC%9E%91%EB%8F%99%EB%B0%A9%EC%8B%9Dcall-by-value-call-by-reference-%EB%B0%98%EB%B3%B5%EB%AC%B8-dncx016z</guid>
            <pubDate>Wed, 01 Oct 2025 01:14:22 GMT</pubDate>
            <description><![CDATA[<h2 id="1-함수functions-핵심-개념">1. 함수(Functions) 핵심 개념</h2>
<h3 id="11-함수의-기본-개념">1.1 함수의 기본 개념</h3>
<ul>
<li><strong>함수(Function)</strong>: 특정 작업을 수행하는 코드 블록</li>
<li><strong>장점</strong>: 코드 재사용성, 모듈화, 가독성 향상</li>
</ul>
<h3 id="12-함수-정의와-호출">1.2 함수 정의와 호출</h3>
<pre><code class="language-python"># 함수 정의
def 함수이름(매개변수):
    # 함수 내용
    return 결과값

# 함수 호출
결과 = 함수이름(인자)
</code></pre>
<h3 id="13-사칙-연산-함수-예제">1.3 사칙 연산 함수 예제</h3>
<pre><code class="language-python">def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

def div(a, b):
    return a / b

# 함수 호출 예제
r1 = mul(a=20, b=30)  # 키워드 인자 사용
r2 = add(a=10, b=r1)
print(r2)  # 출력: 610
</code></pre>
<h3 id="14-온도-변환기-함수-예제">1.4 온도 변환기 함수 예제</h3>
<pre><code class="language-python">def printOptions():
    print(&quot;&#39;c&#39;섭씨온도에서 화씨온도로 변환&quot;)
    print(&quot;&#39;f&#39;화씨온도에서 섭씨온도로 변환&quot;)
    print(&quot;&#39;q&#39;종료&quot;)
    print(&quot;=&quot;*30)

def C2F(c_temp):  # 섭씨 온도를 화씨 온도로 변환
    return 9.0 / 5.0 * c_temp + 32

def F2C(f_temp):  # 화씨 온도를 섭씨 온도로 변환
    return (f_temp - 32.0) * 5.0 / 9.0

# 사용 예시
printOptions()
choice = input(&quot;메뉴에서 선택하세요.&quot;)
if choice == &quot;c&quot;:
    temp = float(input(&quot;섭씨온도: &quot;))
    print(&quot;화씨온도:&quot;, C2F(temp))
elif choice == &quot;f&quot;:
    temp = float(input(&quot;화씨온도: &quot;))
    print(&quot;섭씨온도:&quot;, F2C(temp))
elif choice == &quot;q&quot;:
    print(&quot;종료합니다.&quot;)
else:
    print(&quot;c, f, q중 하나를 입력하시오.&quot;)
</code></pre>
<h2 id="2-함수의-변수-작동-방식">2. 함수의 변수 작동 방식</h2>
<h3 id="21-call-by-value-vs-call-by-reference">2.1 Call-by-value vs Call-by-reference</h3>
<p><strong>Call-by-value (값에 의한 전달)</strong></p>
<ul>
<li>변수의 값을 복사하여 함수에 전달</li>
<li>함수 내에서 값을 변경해도 원본 변수에 영향 없음</li>
<li>숫자, 문자열과 같은 불변(immutable) 타입에 적용</li>
</ul>
<pre><code class="language-python">def modify(n):
    print(&quot;함수 내부 n id =&quot;, id(n))
    print(&quot;함수 내부 n value =&quot;, n)
    n = n + 1
    print(&quot;함수 n = n +1실행 후 내부 n id =&quot;, id(n))
    print(&quot;함수 n = n +1실행 후 내부 n value =&quot;, n)

k = 10
print(&quot;함수 외부 (1) k id =&quot;, id(k))
print(&quot;함수 외부 (1) k value =&quot;, k)
modify(k)
print(&quot;함수 외부 (2) k id =&quot;, id(k))
print(&quot;함수 외부 (2) k value =&quot;, k)
</code></pre>
<p><strong>Call-by-reference (참조에 의한 전달)</strong></p>
<ul>
<li>변수의 참조(메모리 주소)를 함수에 전달</li>
<li>함수 내에서 변경 시 원본 변수도 변경됨</li>
<li>리스트와 같은 가변(mutable) 타입에 적용</li>
</ul>
<pre><code class="language-python">def modify2(li):
    print(&quot;함수 내부 li id =&quot;, id(li))
    print(&quot;함수 내부 li =&quot;, li)
    li += [100, 200]  # 원본 리스트 변경
    print(&quot;함수 li += [100, 200]실행 후 내부 li id =&quot;, id(li))
    print(&quot;함수 li += [100, 200]실행 후 내부 li =&quot;, li)

list = [1, 2, 3, 4, 5]
print(&quot;함수 호출 전 외부 list id =&quot;, id(list))
print(&quot;함수 호출 전 외부 list =&quot;, list)
modify2(list)
print(&quot;함수 호출 후 외부 list id =&quot;, id(list))
print(&quot;함수 호출 후 외부 list =&quot;, list)  # [1, 2, 3, 4, 5, 100, 200]
</code></pre>
<p><strong>참고</strong>: 객체 재할당은 새로운 객체를 생성하므로 참조가 끊어짐</p>
<pre><code class="language-python">def modify2(li):
    print(&quot;함수 내부 li id =&quot;, id(li))
    print(&quot;함수 내부 li =&quot;, li)
    li = [100, 200]  # 새로운 객체 할당 (원본 변경 안 됨)
    print(&quot;함수 li = [100, 200]실행 후 내부 li id =&quot;, id(li))
    print(&quot;함수 li = [100, 200]실행 후 내부 li =&quot;, li)

list = [1, 2, 3, 4, 5]
modify2(list)
print(&quot;함수 호출 후 외부 list =&quot;, list)  # [1, 2, 3, 4, 5]
</code></pre>
<h3 id="22-지역-변수와-전역-변수">2.2 지역 변수와 전역 변수</h3>
<p><strong>지역 변수 (Local Variable)</strong></p>
<ul>
<li>함수 내부에서 선언된 변수</li>
<li>함수 내부에서만 사용 가능</li>
<li>함수 실행이 끝나면 소멸</li>
</ul>
<pre><code class="language-python">def sub():
    s = &quot;바나나가 좋음!&quot;  # 지역 변수
    print(s)

sub()
# print(s)  # 오류: 지역 변수는 함수 외부에서 접근 불가
</code></pre>
<p><strong>전역 변수 (Global Variable)</strong></p>
<ul>
<li>함수 외부에서 선언된 변수</li>
<li>프로그램 전체에서 접근 가능</li>
<li>함수 내부에서도 사용 가능 (단, 수정은 global 키워드 필요)</li>
</ul>
<p><strong>global 키워드</strong>: 함수 내에서 전역 변수를 수정할 때 사용</p>
<pre><code class="language-python">s = &quot;사과가 좋음!&quot;  # 전역 변수

def sub():
    print(&quot;함수 내부 :&quot;, s)  # 전역 변수 사용 가능

sub()
print(&quot;함수 외부 :&quot;, s)
</code></pre>
<pre><code class="language-python">def sub():
    global s  # 전역 변수 s를 사용하겠다고 선언//글로벌썻으니까 이거이제 걍 연결됏다고간주 ㄱㄱ
    print(&quot;함수 내부 (외부로 부터 전달받음) : s -&gt;&quot;, s)
    s = &quot;바나나가 좋음!&quot;  # 전역 변수 값 변경
    print(&quot;함수 내부 (내부에서 수정됨) : s -&gt;&quot;, s)

s = &quot;사과가 좋음!&quot;
print(&quot;함수 외부 (함수 실행 전) : s -&gt;&quot;, s)
sub()
print(&quot;함수 외부 (함수 실행 후) : s -&gt;&quot;, s)  # &quot;바나나가 좋음!&quot; 출력
</code></pre>
<h3 id="23-람다-함수-lambda-function">2.3 람다 함수 (Lambda Function)</h3>
<ul>
<li><p>익명 함수: 이름이 없는 한 줄짜리 함수</p>
<p>  ◦ 여러 개의 argument를 가지고 있으나 return value는 하나만 있어야 함
  ◦ 익명함수 내에서는 print()를 호출할 수 없고 간단한 계산만 가능함
  ◦ global variables를 참조할 수 없음
  ◦ 1개의 라인으로 구성되는 함수임</p>
</li>
<li><p><code>lambda</code> 키워드로 생성</p>
</li>
<li><p>간단한 계산에 유용</p>
</li>
</ul>
<pre><code class="language-python">sum = lambda x, y: x + y
print(&quot;정수의 합 :&quot;, sum(10, 20))  # 정수의 합 : 30
print(&quot;정수의 합 :&quot;, sum(20, 20))  # 정수의 합 : 40
</code></pre>
<h2 id="3-반복문loops-핵심-개념">3. 반복문(Loops) 핵심 개념</h2>
<h3 id="31-반복문-기본-개념">3.1 반복문 기본 개념</h3>
<ul>
<li>동일한 작업을 여러 번 수행하는 구조</li>
<li>컴퓨터는 반복 작업을 실수 없이 빠르게 수행</li>
</ul>
<h3 id="32-for-반복문">3.2 for 반복문</h3>
<p><strong>기본 구조</strong>:</p>
<pre><code class="language-python">for 변수 in 시퀀스:
    # 반복할 코드</code></pre>
<p><strong>예제</strong>:</p>
<pre><code class="language-python"># 문자열 &quot;환영합니다&quot;를 5번 출력
for x in range(5):
    print(&quot;환영합니다.&quot;)

# 리스트의 각 요소에 접근
for name in [&quot;철수&quot;, &quot;영희&quot;, &quot;길동&quot;, &quot;유신&quot;]:
    print(&quot;안녕! &quot; + name)</code></pre>
<h3 id="33-range-함수">3.3 range() 함수</h3>
<ul>
<li>특정 범위의 정수 시퀀스를 생성하는 함수</li>
<li><code>range(stop)</code>: 0부터 stop-1까지의 정수 생성</li>
<li><code>range(start, stop)</code>: start부터 stop-1까지의 정수 생성</li>
<li><code>range(start, stop, step)</code>: start부터 stop-1까지 step 간격으로 정수 생성</li>
</ul>
<pre><code class="language-python"># 0부터 9까지 출력
for x in range(10):
    print(x, end=&quot; &quot;)  # 0 1 2 3 4 5 6 7 8 9

# 0부터 9까지의 합계 계산
sum = 0
for x in range(10):
    sum = sum + x
print(sum)  # 45</code></pre>
<h2 id="4-예상-문제-및-풀이">4. 예상 문제 및 풀이</h2>
<h3 id="문제-1-함수-개념-이해하기">문제 1: 함수 개념 이해하기</h3>
<p>다음 코드의 출력 결과는?</p>
<pre><code class="language-python">def calculate_area(radius):
    result = 3.14 * radius**2
    return result

r = float(input(&quot;원의 반지름: &quot;))  # 사용자가 10.0 입력
area = calculate_area(r)
print(area)</code></pre>
<ul>
<li><p><strong>답</strong>:</p>
<p>   314.0</p>
</li>
</ul>
<h3 id="문제-2-지역-변수와-전역-변수">문제 2: 지역 변수와 전역 변수</h3>
<p>다음 코드의 출력 결과는?</p>
<pre><code class="language-python">def sub(x, y):
    global a
    a = 7
    x, y = y, x
    b = 3
    print(&quot;함수 내부 a : %d, b : %d, x : %d, y : %d&quot; % (a, b, x, y))

a, b, x, y = 1, 2, 3, 4
sub(x, y)
print(&quot;함수 외부 a : %d, b : %d, x : %d, y : %d&quot; % (a, b, x, y))</code></pre>
<ul>
<li><p><strong>답</strong>:</p>
<pre><code>  함수 내부 a : 7, b : 3, x : 4, y : 3
  함수 외부 a : 7, b : 2, x : 3, y : 4</code></pre></li>
</ul>
<h3 id="문제-3-call-by-value와-call-by-reference">문제 3: Call-by-value와 Call-by-reference</h3>
<p>다음 코드의 출력 결과는?</p>
<pre><code class="language-python">def modify(mylist):
    print(&quot;함수 내부에서의 mylist:&quot;, mylist)
    mylist = [1, 2, 3, 4]
    print(&quot;함수 내부에서의 mylist:&quot;, mylist)
    return

mylist = [10, 20, 30, 40]
modify(mylist)
print(&quot;함수 외부에서의 mylist:&quot;, mylist)
</code></pre>
<ul>
<li><p><strong>답</strong>:</p>
<pre><code>  함수 내부에서의 mylist: [10, 20, 30, 40]
  함수 내부에서의 mylist: [1, 2, 3, 4]
  함수 외부에서의 mylist: [10, 20, 30, 40]
</code></pre></li>
</ul>
<h3 id="문제-4-for-반복문과-range-함수">문제 4: for 반복문과 range 함수</h3>
<p>다음 코드를 실행하면 총 몇 번의 반복이 수행되는가?</p>
<pre><code class="language-python">sum = 0
for i in range(1, 10, 2):
    for j in range(2, 5):
        sum += i * j
print(sum)
</code></pre>
<ul>
<li><p><strong>답</strong>:</p>
<p>  5 × 3 = 15번 (i는 1,3,5,7,9의 5개 값, j는 2,3,4의 3개 값)</p>
</li>
</ul>
<h3 id="문제-5-함수-작성-문제">문제 5: 함수 작성 문제</h3>
<p>다음과 같은 기능을 하는 함수를 작성하시오:</p>
<ol>
<li>사용자로부터 두 개의 정수를 입력받는 함수</li>
<li>입력받은 두 정수 사이의 모든 정수의 합을 계산하는 함수</li>
<li>결과를 출력하는 함수</li>
</ol>
<ul>
<li><p><strong>답</strong>:</p>
<pre><code class="language-python">  def get_two_integers():
      num1 = int(input(&quot;첫 번째 정수를 입력하세요: &quot;))
      num2 = int(input(&quot;두 번째 정수를 입력하세요: &quot;))
      return num1, num2

  def calculate_sum_between(a, b):
      # 항상 작은 수부터 큰 수까지 더하기
      if a &gt; b:
          a, b = b, a
      total = 0
      for i in range(a, b + 1):
          total += i
      return total

  def print_result(result):
      print(&quot;두 정수 사이의 모든 정수의 합:&quot;, result)

  def main():
      num1, num2 = get_two_integers()
      sum_result = calculate_sum_between(num1, num2)
      print_result(sum_result)

  main()
</code></pre>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter02. 조건문, 함수]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter02.-%EC%A1%B0%EA%B1%B4%EB%AC%B8-%ED%95%A8%EC%88%98</link>
            <guid>https://velog.io/@lullaby_/PythonChapter02.-%EC%A1%B0%EA%B1%B4%EB%AC%B8-%ED%95%A8%EC%88%98</guid>
            <pubDate>Wed, 01 Oct 2025 01:12:52 GMT</pubDate>
            <description><![CDATA[<h2 id="1-조건문-conditional-statement">1. 조건문 (Conditional Statement)</h2>
<h3 id="11-핵심-개념">1.1 핵심 개념</h3>
<ul>
<li>조건문은 특정 조건에 따라 코드 실행을 제어하는 구문</li>
<li>파이썬에서는 <code>if</code>, <code>elif</code>, <code>else</code> 키워드를 사용</li>
<li>조건의 참/거짓 여부에 따라 실행 흐름이 달라짐</li>
</ul>
<h3 id="12-if-elif-else-구문">1.2 if-elif-else 구문</h3>
<pre><code class="language-python">if 조건1:
    # 조건1이 참일 때 실행할 코드
elif 조건2:
    # 조건1이 거짓이고 조건2가 참일 때 실행할 코드
else:
    # 모든 조건이 거짓일 때 실행할 코드
</code></pre>
<h3 id="13-중첩-조건문">1.3 중첩 조건문</h3>
<pre><code class="language-python">if 조건1:
    if 조건2:
        # 조건1과 조건2가 모두 참일 때 실행할 코드
    else:
        # 조건1은 참이지만 조건2가 거짓일 때 실행할 코드
else:
    # 조건1이 거짓일 때 실행할 코드
</code></pre>
<h3 id="14-논리-연산자">1.4 논리 연산자</h3>
<ul>
<li><code>and</code>: 양쪽 조건이 모두 참일 때만 참</li>
<li><code>or</code>: 양쪽 조건 중 하나라도 참이면 참</li>
<li><code>not</code>: 조건의 결과를 반대로 바꿈</li>
</ul>
<pre><code class="language-python">if 조건1 and 조건2:
    # 조건1과 조건2가 모두 참일 때 실행
if 조건1 or 조건2:
    # 조건1이나 조건2 중 하나라도 참일 때 실행
if not 조건:
    # 조건이 거짓일 때 실행
</code></pre>
<h3 id="15-예제-학점-계산기">1.5 예제: 학점 계산기</h3>
<pre><code class="language-python">score = int(input(&quot;성적을 입력하시오: &quot;))
if score &gt;= 90:
    print(&quot;학점 A&quot;)
elif score &gt;= 80:
    print(&quot;학점 B&quot;)
elif score &gt;= 70:
    print(&quot;학점 C&quot;)
elif score &gt;= 60:
    print(&quot;학점 D&quot;)
else:
    print(&quot;학점 F&quot;)
</code></pre>
<h3 id="16-예제-월별-일수-출력">1.6 예제: 월별 일수 출력</h3>
<pre><code class="language-python">month = int(input(&quot;월을 입력하시오: &quot;))
if month == 2:
    print(month, &quot;월의 날수는 28일&quot;)
elif month in [4, 6, 9, 11]:
    print(month, &quot;월의 일수는 30일&quot;)
elif month in [1, 3, 5, 7, 8, 10, 12]:
    print(month, &quot;월의 일수는 31일&quot;)
else:
    print(month, &quot;월은 없습니다.&quot;)
</code></pre>
<h3 id="17-예외-처리">1.7 예외 처리</h3>
<pre><code class="language-python">try:
    예외가 발생할 가능성이 있는 코드

except:
    예외가 발생했을 때 실행할 코드
    (필요에 따라 except 절을 추가로 작성)</code></pre>
<pre><code class="language-python">try:
    # 예외가 발생할 수 있는 코드
    x = int(input(&#39;숫자를 입력하세요: &#39;))
    y = 10 / x
    print(y)
except ValueError:
    # 값 오류 발생 시 실행되는 코드
    print(&#39;숫자가 아닌 값을 입력했습니다.&#39;)
except ZeroDivisionError:
    # 0으로 나누기 시도 시 실행되는 코드
    print(&#39;0으로 나눌 수 없습니다.&#39;)
except:
    # 다른 모든 예외 발생 시 실행되는 코드
    print(&#39;알 수 없는 오류가 발생했습니다.&#39;)
</code></pre>
<h2 id="2-함수-functions">2. 함수 (Functions)</h2>
<h3 id="21-핵심-개념">2.1 핵심 개념</h3>
<ul>
<li>함수: 특정 작업을 수행하는 명령어들의 모음에 이름을 붙인 것</li>
<li>함수는 코드의 재사용성을 높이고 가독성을 향상시킴</li>
<li>내장 함수와 사용자 정의 함수가 있음</li>
</ul>
<h3 id="22-함수-정의-및-호출">2.2 함수 정의 및 호출</h3>
<pre><code class="language-python">def 함수이름(매개변수1, 매개변수2, ...):
    # 함수 본문
    return 반환값  # 선택적
</code></pre>
<pre><code class="language-python"># 함수 호출
결과변수 = 함수이름(인수1, 인수2, ...)
</code></pre>
<h3 id="23-매개변수와-인수">2.3 매개변수와 인수</h3>
<ul>
<li>매개변수(parameter): 함수 정의에서 입력으로 받는 변수</li>
<li>인수(argument): 함수 호출 시 전달하는 실제 값</li>
</ul>
<h3 id="24-반환값">2.4 반환값</h3>
<ul>
<li><code>return</code> 문을 사용하여 함수의 결과를 반환</li>
<li><code>return</code> 문이 없으면 함수는 <code>None</code>을 반환</li>
<li>여러 값을 한 번에 반환할 수 있음</li>
</ul>
<pre><code class="language-python">def get_values():
    return 1, 2, 3

a, b, c = get_values()
</code></pre>
<h3 id="25-기본-인수">2.5 기본 인수</h3>
<ul>
<li>매개변수에 기본값을 설정할 수 있음</li>
<li>함수 호출 시 값을 전달하지 않으면 기본값이 사용됨</li>
</ul>
<pre><code class="language-python">def greet(name, msg=&quot;안녕하세요&quot;):
    print(name + &quot;, &quot; + msg)

greet(&quot;영희&quot;)  # 기본 메시지 사용
greet(&quot;영희&quot;, &quot;오랜만이에요&quot;)  # 사용자 지정 메시지 사용
</code></pre>
<h3 id="26-키워드-인수">2.6 키워드 인수</h3>
<ul>
<li>인수의 순서와 상관없이 매개변수 이름으로 값을 전달</li>
</ul>
<pre><code class="language-python">def calculate(x, y, z):
    return x + y + z

result = calculate(y=20, x=10, z=30)  # 순서 상관없이 매개변수 이름으로 전달
</code></pre>
<h3 id="27-모듈-사용">2.7 모듈 사용</h3>
<ul>
<li>함수, 변수, 클래스 등을 모아놓은 파일</li>
<li><code>import</code> 문을 사용하여 모듈을 가져옴</li>
</ul>
<pre><code class="language-python">import math
radius = 10
area = math.pi * radius ** 2

# 모듈에서 특정 함수나 변수만 가져오기
from math import pi, sqrt
area = pi * radius ** 2
</code></pre>
<h2 id="3-예상-문제-및-풀이">3. 예상 문제 및 풀이</h2>
<h3 id="조건문-관련-문제">조건문 관련 문제</h3>
<h3 id="문제-1-조건문-오류-찾기">문제 1: 조건문 오류 찾기</h3>
<p>다음 코드의 오류를 찾아 수정하세요. 이 코드는 학점을 계산하는 프로그램입니다.</p>
<pre><code class="language-python">score = int(input(&quot;성적을 입력하시오: &quot;))
if score &gt;= 90:
    print(&quot;학점 A&quot;)
elif score &gt;= 60:
    print(&quot;학점 D&quot;)
elif score &gt;= 70:
    print(&quot;학점 C&quot;)
elif score &gt;= 80:
    print(&quot;학점 B&quot;)
else:
    print(&quot;학점 F&quot;)
</code></pre>
<ul>
<li><p><strong>정답:</strong></p>
<p>  조건문의 순서가 잘못되었습니다. 조건을 큰 값부터 작은 값 순으로 검사해야 합니다.</p>
<pre><code class="language-python">  score = int(input(&quot;성적을 입력하시오: &quot;))
  if score &gt;= 90:
      print(&quot;학점 A&quot;)
  elif score &gt;= 80:
      print(&quot;학점 B&quot;)
  elif score &gt;= 70:
      print(&quot;학점 C&quot;)
  elif score &gt;= 60:
      print(&quot;학점 D&quot;)
  else:
      print(&quot;학점 F&quot;)
</code></pre>
</li>
</ul>
<h3 id="문제-2-조건문-실행-결과-예측">문제 2: 조건문 실행 결과 예측</h3>
<p>다음 코드의 실행 결과를 예측하세요.</p>
<pre><code class="language-python">age = 20
height = 180
if (age &gt;= 10 and height &gt;= 165):
    print(&quot;놀이 기구를 탈 수 있습니다.&quot;)
else:
    print(&quot;놀이 기구를 탈 수 없습니다.&quot;)
</code></pre>
<ul>
<li><p><strong>정답:</strong></p>
<p>  &quot;놀이 기구를 탈 수 있습니다.&quot;가 출력됩니다. age가 20이고 height가 180이므로 두 조건(age &gt;= 10, height &gt;= 165)을 모두 만족합니다.</p>
</li>
</ul>
<h3 id="문제-3-예외-처리-코드-작성"><strong>문제 3: 예외 처리 코드 작성</strong></h3>
<p>사용자로부터 월을 입력받아 해당 월의 일수를 출력하는 프로그램을 작성하세요. 단, 사용자가 숫자가 아닌 값을 입력할 경우 예외 처리를 하고, 1~12 이외의 숫자를 입력할 경우에도 적절한 메시지를 출력하세요.</p>
<ul>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  try:
      month = int(input(&quot;월을 입력하시오: &quot;))
      if month == 2:
          print(month, &quot;월의 날수는 28일&quot;)
      elif month in [4, 6, 9, 11]:
          print(month, &quot;월의 일수는 30일&quot;)
      elif month in [1, 3, 5, 7, 8, 10, 12]:
          print(month, &quot;월의 일수는 31일&quot;)
      else:
          print(month, &quot;월은 없습니다.&quot;)
  except ValueError:
      print(&quot;입력값이 숫자 타입의 월이 아닙니다.&quot;)
      print(&quot;월은 3월로 자동 입력됩니다.&quot;)
      month = 3
      print(month, &quot;월의 일수는 31일&quot;)
</code></pre>
</li>
</ul>
<h3 id="함수-관련-문제">함수 관련 문제</h3>
<h3 id="문제-4-함수-구현하기">문제 4: 함수 구현하기</h3>
<p>두 숫자 중 큰 수를 반환하는 함수 <code>get_max()</code>를 구현하세요.</p>
<ul>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  def get_max(x, y):
      if x &gt; y:
          return x
      else:
          return y

  # 테스트
  print(get_max(10, 20))  # 20 출력
  print(get_max(30, 15))  # 30 출력
</code></pre>
</li>
</ul>
<h3 id="문제-5-함수-오류-찾기">문제 5: 함수 오류 찾기</h3>
<p>다음 함수에서 오류를 찾아 수정하세요.</p>
<pre><code class="language-python">def power(x, y):
    result = 1
    result = result * x * y
    return result

print(power(10, 2))
</code></pre>
<ul>
<li><strong>정답:</strong></li>
</ul>
<pre><code>거듭제곱 계산 방식이 잘못되었습니다. x의 y제곱은 x를 y번 곱해야 합니다.

```python
def power(x, y):
    result = x ** y  # 또는 result = pow(x, y)
    return result

print(power(10, 2))  # 100 출력

```</code></pre><h3 id="문제-6-함수와-모듈-사용하기">문제 6: 함수와 모듈 사용하기</h3>
<p>math 모듈을 사용하여 반지름이 주어졌을 때 구의 부피를 계산하는 함수 <code>sphere_volume()</code>을 작성하세요.</p>
<ul>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  import math

  def sphere_volume(radius):
      volume = (4.0 / 3.0) * math.pi * radius ** 3
      return volume

  # 테스트
  radius = float(input(&quot;구의 반지름을 입력하시오: &quot;))
  print(sphere_volume(radius))
</code></pre>
</li>
</ul>
<h3 id="문제-7-기본-인수-사용하기">문제 7: 기본 인수 사용하기</h3>
<p>이름과 메시지를 인수로 받아 인사말을 출력하는 함수 <code>greet()</code>을 작성하세요. 메시지에는 기본값 &quot;별일없죠?&quot;를 사용하세요.</p>
<ul>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  def greet(name, msg=&quot;별일없죠?&quot;):
      print(&quot;안녕 &quot; + name + &quot;, &quot; + msg)

  # 테스트
  greet(&quot;영희&quot;)  # &quot;안녕 영희, 별일없죠?&quot; 출력
  greet(&quot;영희&quot;, &quot;지금 집에 있니?&quot;)  # &quot;안녕 영희, 지금 집에 있니?&quot; 출력
</code></pre>
</li>
</ul>
<h2 id="4-실전-대비-종합-문제">4. 실전 대비 종합 문제</h2>
<h3 id="문제-1-종합-조건문-문제">문제 1: 종합 조건문 문제</h3>
<p>사용자로부터 나이와 키를 입력받아 다음 조건에 따라 적절한 메시지를 출력하는 프로그램을 작성하세요.</p>
<ul>
<li><p>나이가 12세 이상이고 키가 140cm 이상이면 &quot;모든 놀이기구를 탈 수 있습니다.&quot;</p>
</li>
<li><p>나이가 10세 이상이고 키가 130cm 이상이면 &quot;대부분의 놀이기구를 탈 수 있습니다.&quot;</p>
</li>
<li><p>그 외에는 &quot;일부 놀이기구만 탈 수 있습니다.&quot;</p>
</li>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  try:
      age = int(input(&quot;나이를 입력하세요: &quot;))
      height = float(input(&quot;키를 입력하세요(cm): &quot;))

      if age &gt;= 12 and height &gt;= 140:
          print(&quot;모든 놀이기구를 탈 수 있습니다.&quot;)
      elif age &gt;= 10 and height &gt;= 130:
          print(&quot;대부분의 놀이기구를 탈 수 있습니다.&quot;)
      else:
          print(&quot;일부 놀이기구만 탈 수 있습니다.&quot;)
  except ValueError:
      print(&quot;나이와 키는 숫자로 입력해야 합니다.&quot;)
</code></pre>
</li>
</ul>
<h3 id="문제-2-종합-함수-문제">문제 2: 종합 함수 문제</h3>
<p>섭씨 온도와 화씨 온도를 상호 변환하는 두 함수 <code>celsius_to_fahrenheit()</code>와 <code>fahrenheit_to_celsius()</code>를 작성하세요. 사용자로부터 변환하고자 하는 온도와 단위(C 또는 F)를 입력받아 변환 결과를 출력하는 프로그램을 작성하세요.</p>
<ul>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  def celsius_to_fahrenheit(temp_c):
      temp_f = (9.0 / 5.0) * temp_c + 32.0
      return temp_f

  def fahrenheit_to_celsius(temp_f):
      temp_c = (5.0 / 9.0) * (temp_f - 32.0)
      return temp_c

  try:
      temp = float(input(&quot;온도를 입력하세요: &quot;))
      unit = input(&quot;단위를 입력하세요(C 또는 F): &quot;)

      if unit.upper() == &quot;C&quot;:
          converted = celsius_to_fahrenheit(temp)
          print(f&quot;{temp}°C는 {converted:.2f}°F입니다.&quot;)
      elif unit.upper() == &quot;F&quot;:
          converted = fahrenheit_to_celsius(temp)
          print(f&quot;{temp}°F는 {converted:.2f}°C입니다.&quot;)
      else:
          print(&quot;단위는 C 또는 F로 입력해야 합니다.&quot;)
  except ValueError:
      print(&quot;온도는 숫자로 입력해야 합니다.&quot;)
</code></pre>
</li>
</ul>
<h3 id="문제-3-예외-처리-응용-문제">문제 3: 예외 처리 응용 문제</h3>
<p>사용자로부터 두 개의 정수를 입력받아 나눗셈을 수행하는 프로그램을 작성하세요. 다음 예외를 처리해야 합니다:</p>
<ul>
<li><p>사용자가 숫자가 아닌 값을 입력할 경우</p>
</li>
<li><p>사용자가 두 번째 숫자로 0을 입력할 경우</p>
</li>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  try:
      num1 = int(input(&quot;첫 번째 정수를 입력하세요: &quot;))
      num2 = int(input(&quot;두 번째 정수를 입력하세요: &quot;))

      result = num1 / num2
      print(f&quot;{num1} / {num2} = {result}&quot;)

  except ValueError:
      print(&quot;입력값이 정수가 아닙니다. 정수를 입력해주세요.&quot;)
  except ZeroDivisionError:
      print(&quot;0으로 나눌 수 없습니다. 두 번째 숫자는 0이 아닌 값을 입력해주세요.&quot;)
  except:
      print(&quot;알 수 없는 오류가 발생했습니다.&quot;)
</code></pre>
</li>
</ul>
<h3 id="문제-4-함수와-조건문-응용-문제">문제 4: 함수와 조건문 응용 문제</h3>
<p>사용자로부터 세 개의 숫자를 입력받아, 가장 큰 수를 반환하는 함수 <code>find_largest()</code>를 작성하세요. 이 함수를 사용하여 최댓값을 출력하는 프로그램을 작성하세요.</p>
<ul>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  def find_largest(a, b, c):
      if a &gt;= b and a &gt;= c:
          return a
      elif b &gt;= a and b &gt;= c:
          return b
      else:
          return c

  try:
      num1 = float(input(&quot;첫 번째 숫자: &quot;))
      num2 = float(input(&quot;두 번째 숫자: &quot;))
      num3 = float(input(&quot;세 번째 숫자: &quot;))

      largest = find_largest(num1, num2, num3)
      print(f&quot;가장 큰 수는 {largest}입니다.&quot;)
  except ValueError:
      print(&quot;유효한 숫자를 입력해주세요.&quot;)
</code></pre>
</li>
</ul>
<h3 id="문제-5-모듈-활용-문제">문제 5: 모듈 활용 문제</h3>
<p>math 모듈을 사용하여 다음 기능을 수행하는 프로그램을 작성하세요:</p>
<ol>
<li>사용자로부터 원의 반지름을 입력받음</li>
<li>원의 둘레와 면적을 계산하여 출력</li>
<li>반지름을 이용해 구의 표면적과 부피를 계산하여 출력</li>
</ol>
<ul>
<li><p><strong>정답:</strong></p>
<pre><code class="language-python">  import math

  def circle_properties(radius):
      circumference = 2 * math.pi * radius
      area = math.pi * radius ** 2
      return circumference, area

  def sphere_properties(radius):
      surface_area = 4 * math.pi * radius ** 2
      volume = (4/3) * math.pi * radius ** 3
      return surface_area, volume

  try:
      radius = float(input(&quot;원의 반지름을 입력하세요: &quot;))

      if radius &lt;= 0:
          print(&quot;반지름은 양수여야 합니다.&quot;)
      else:
          circ, area = circle_properties(radius)
          surf_area, volume = sphere_properties(radius)

          print(f&quot;원의 둘레: {circ:.2f}&quot;)
          print(f&quot;원의 면적: {area:.2f}&quot;)
          print(f&quot;구의 표면적: {surf_area:.2f}&quot;)
          print(f&quot;구의 부피: {volume:.2f}&quot;)

  except ValueError:
      print(&quot;유효한 숫자를 입력해주세요.&quot;)
</code></pre>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[Python/Chapter01. 파이썬 기초]]></title>
            <link>https://velog.io/@lullaby_/PythonChapter01.-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EA%B8%B0%EC%B4%88</link>
            <guid>https://velog.io/@lullaby_/PythonChapter01.-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EA%B8%B0%EC%B4%88</guid>
            <pubDate>Wed, 01 Oct 2025 01:03:39 GMT</pubDate>
            <description><![CDATA[<h2 id="i-파이썬-기초">I. 파이썬 기초</h2>
<h3 id="핵심-개념">핵심 개념</h3>
<ol>
<li><strong>파이썬 소개</strong><ul>
<li>1991년 귀도 반 로섬이 개발한 대화형 프로그래밍 언어</li>
<li>특징: 생산성이 뛰어남, 문법이 쉬움, 초보자에게 적합, 다양한 플랫폼 지원</li>
</ul>
</li>
<li><strong>파이썬의 장점</strong><ul>
<li>문법이 직관적이고 이해하기 쉬움</li>
<li>다양한 환경에서 사용 가능</li>
<li>라이브러리가 풍부함</li>
<li>바로 결과를 확인할 수 있음</li>
</ul>
</li>
</ol>
<h2 id="ii-변수와-연산자">II. 변수와 연산자</h2>
<h3 id="핵심-개념-1">핵심 개념</h3>
<ol>
<li><strong>변수</strong><ul>
<li>정의: 값을 저장하는 공간(메모리)</li>
<li>변수 생성: <code>변수명 = 값</code> 형태로 할당</li>
<li>변수 작명 규칙:<ul>
<li>영문자, 숫자, 언더바(_)로 구성</li>
<li>첫 글자는 숫자 불가</li>
<li>대소문자 구분</li>
<li>중간에 공백 불가</li>
<li>특수문자 불가</li>
</ul>
</li>
<li>낙타체 표기법: 첫 글자는 소문자, 나머지 단어의 첫 글자는 대문자 (예: myNewCar)</li>
</ul>
</li>
<li><strong>상수</strong><ul>
<li>변경되지 않는 고정된 값</li>
<li>관례적으로 대문자로 표기 (예: PI = 3.141592)</li>
</ul>
</li>
<li><strong>데이터 타입</strong><ul>
<li>정수(int): -2, -1, 0, 1, 2</li>
<li>실수(float): 3.2, 3.14, 0.12</li>
<li>문자열(str): &#39;Hello World!&#39;, &quot;1234&quot;</li>
<li>타입 확인: <code>type()</code> 함수 사용</li>
</ul>
</li>
<li><strong>산술 연산자</strong><ul>
<li>덧셈: <code>+</code></li>
<li>뺄셈: -</li>
<li>곱셈: *</li>
<li>나눗셈(실수형): <code>/</code> (예: 7/4 = 1.75)</li>
<li>나눗셈(정수형): <code>//</code> (예: 7//4 = 1)</li>
<li>나머지: <code>%</code> (예: 7%4 = 3)</li>
<li>거듭제곱: <code>*</code>* (예: 2**3 = 8)</li>
</ul>
</li>
<li><strong>연산자 우선순위</strong><ul>
<li>괄호 &gt; 거듭제곱 &gt; 곱셈/나눗셈/나머지 &gt; 덧셈/뺄셈</li>
</ul>
</li>
<li><strong>사용자 입력</strong><ul>
<li><code>input()</code> 함수: 문자열 입력</li>
<li>정수 변환: <code>int(input())</code></li>
<li>실수 변환: <code>float(input())</code></li>
</ul>
</li>
<li><strong>주석</strong><ul>
<li>한 줄 주석: <code>#</code></li>
<li>여러 줄 주석: <code>&#39;&#39;&#39;</code> 또는 <code>&quot;&quot;&quot;</code></li>
</ul>
</li>
</ol>
<h2 id="iii-조건문">III. 조건문</h2>
<h3 id="핵심-개념-2">핵심 개념</h3>
<ol>
<li><p><strong>관계 연산자</strong></p>
<ul>
<li>동등: <code>==</code></li>
<li>같지 않음: <code>!=</code></li>
<li>크다: <code>&gt;</code></li>
<li>작다: <code>&lt;</code></li>
<li>크거나 같다: <code>&gt;=</code></li>
<li>작거나 같다: <code>&lt;=</code></li>
</ul>
</li>
<li><p><strong>if 문</strong></p>
<ul>
<li><p>기본 구조:</p>
<pre><code class="language-python">  if 조건:    # 조건이 참일 때 실행할 코드else:    # 조건이 거짓일 때 실행할 코드
</code></pre>
</li>
<li><p>else 부분은 생략 가능</p>
</li>
</ul>
</li>
<li><p><strong>들여쓰기</strong></p>
<ul>
<li>파이썬에서는 들여쓰기로 코드 블록을 구분</li>
<li>일반적으로 4칸 또는 탭 사용</li>
</ul>
</li>
</ol>
<h2 id="실습-예제">실습 예제</h2>
<h3 id="1-변수와-연산자">1. 변수와 연산자</h3>
<pre><code class="language-python"># 변수 사용 예제
width = 10
height = 20
area = width * height
print(area)  # 출력: 200

# 연산자 사용 예제
x = 2.0
y = 3.0 * x**2 + 7.0 * x + 9.0
print(y)  # 출력: 35.0

# 사용자 입력 예제
name = input(&quot;What is your name? &quot;)
print(&quot;Hello, Mr. &quot;, name)
</code></pre>
<h3 id="2-조건문">2. 조건문</h3>
<pre><code class="language-python"># 홀수/짝수 판별
number = int(input(&quot;정수를 입력하시오: &quot;))
if (number % 2) == 0:
    print(&quot;입력된 정수는 짝수입니다.&quot;)
else:
    print(&quot;입력된 정수는 홀수입니다.&quot;)

# 두 수 중 큰 수 찾기
x = int(input(&quot;첫 번째 정수: &quot;))
y = int(input(&quot;두 번째 정수: &quot;))
if x &gt; y:
    print(&quot;큰 수는&quot;, x)
else:
    print(&quot;큰 수는&quot;, y)

# 할인 금액 계산
sales = int(input(&quot;구입 금액을 입력하시오: &quot;))
discount = 0
if sales &gt;= 100000:
    discount = sales * 0.05
print(&quot;쇼핑 금액은&quot;, sales, &quot;원 입니다.&quot;)
print(&quot;할인된 금액은&quot;, discount, &quot;원 이고,&quot;)
print(&quot;최종 지불 금액은&quot;, sales-discount, &quot;원 입니다.&quot;)
</code></pre>
<h2 id="예상-문제-및-풀이">예상 문제 및 풀이</h2>
<h3 id="객관식-문제">객관식 문제</h3>
<ol>
<li><p><strong>파이썬에서 변수명으로 올바른 것은?</strong></p>
<ul>
<li><p>a) 1stName</p>
</li>
<li><p>b) my-name</p>
</li>
<li><p>c) userName</p>
</li>
<li><p>d) user@name</p>
</li>
<li><p>답:</p>
<p>  c) userName</p>
</li>
</ul>
</li>
<li><p><strong>다음 중 파이썬의 특징이 아닌 것은?</strong></p>
<ul>
<li><p>a) 인터프리터 언어이다</p>
</li>
<li><p>b) 문법이 복잡하고 이해하기 어렵다</p>
</li>
<li><p>c) 다양한 플랫폼에서 사용 가능하다</p>
</li>
<li><p>d) 다양한 라이브러리를 제공한다</p>
</li>
<li><p>답:</p>
<p>  b) 문법이 복잡하고 이해하기 어렵다</p>
</li>
</ul>
</li>
<li><p><strong>다음 중 파이썬에서 정수 나눗셈의 결과는?</strong></p>
<ul>
<li><p>a) 7 / 4 = 1.75</p>
</li>
<li><p>b) 7 // 4 = 1</p>
</li>
<li><p>c) 7 % 4 = 3</p>
</li>
<li><p>d) 7 ** 4 = 2401</p>
</li>
<li><p>답:</p>
<p>  b) 7 // 4 = 1</p>
</li>
</ul>
</li>
<li><p><strong>파이썬에서 주석을 표시하는 방법은?</strong></p>
<ul>
<li><p>a) // 주석</p>
</li>
<li><p>b) /* 주석 */</p>
</li>
<li><p>c) # 주석</p>
</li>
<li><p>d) <!-- 주석 --></p>
</li>
<li><p>답:</p>
<p>  c) # 주석</p>
</li>
</ul>
</li>
<li><p><strong>파이썬에서 조건문의 올바른 구문은?</strong></p>
<ul>
<li><p>a) if (condition) { statements }</p>
</li>
<li><p>b) if condition: statements</p>
</li>
<li><p>c) if condition then statements</p>
</li>
<li><p>d) if (condition) statements endif</p>
</li>
<li><p>답:</p>
<p>  b) if condition: statements</p>
</li>
</ul>
</li>
</ol>
<h3 id="주관식-문제">주관식 문제</h3>
<ol>
<li><p><strong>파이썬에서 변수의 타입을 확인하는 함수는?</strong></p>
<p> 답: type()</p>
</li>
<li><p><strong>파이썬에서 사용자로부터 입력을 받는 함수는?</strong></p>
<p> 답: input()</p>
</li>
<li><p><strong>파이썬에서 거듭제곱을 표현하는 연산자는?</strong></p>
<p> 답: **</p>
</li>
<li><p><strong>파이썬에서 들여쓰기의 역할은?</strong></p>
<p> 답: 코드 블록의 구분</p>
</li>
<li><p><strong>파이썬에서 문자열을 정수로 변환하는 함수는?</strong></p>
<p> 답: int()</p>
</li>
</ol>
<h3 id="실습-문제">실습 문제</h3>
<ol>
<li><p><strong>나이 계산기</strong></p>
<p> 사용자로부터 태어난 연도를 입력받아 현재 나이(2025년 기준)를 계산하는 프로그램을 작성하세요.</p>
<pre><code class="language-python"> #내 답변
 year = int(input(&quot;태어난 연도를 입력하세요.: &quot;))
 age = 2025 - year + 1
 print(age)</code></pre>
<pre><code class="language-python"> birth_year = int(input(&quot;태어난 연도를 입력하세요: &quot;))
 current_year = 2025
 age = current_year - birth_year
 print(&quot;당신의 나이는&quot;, age, &quot;세입니다.&quot;)
</code></pre>
</li>
<li><p><strong>온도 변환기</strong></p>
<p> 사용자로부터 섭씨 온도를 입력받아 화씨 온도로 변환하는 프로그램을 작성하세요. (화씨 = 섭씨 * 9/5 + 32)</p>
<pre><code class="language-python"> celsius = float(input(&quot;섭씨 온도를 입력하세요: &quot;))
 fahrenheit = celsius * 9/5 + 32
 print(&quot;섭씨&quot;, celsius, &quot;도는 화씨&quot;, fahrenheit, &quot;도입니다.&quot;)
</code></pre>
</li>
<li><p><strong>학점 계산기</strong></p>
<p> 사용자로부터 시험 점수를 입력받아 학점을 출력하는 프로그램을 작성하세요.</p>
<ul>
<li><p>90점 이상: A</p>
</li>
<li><p>80점 이상: B</p>
</li>
<li><p>70점 이상: C</p>
</li>
<li><p>60점 이상: D</p>
</li>
<li><p>60점 미만: F</p>
<pre><code class="language-python">score = int(input(&quot;시험 점수를 입력하세요: &quot;))
if score &gt;= 90:
  grade = &quot;A&quot;
elif score &gt;= 80:
  grade = &quot;B&quot;
elif score &gt;= 70:
  grade = &quot;C&quot;
elif score &gt;= 60:
  grade = &quot;D&quot;
else:
  grade = &quot;F&quot;
print(&quot;당신의 학점은&quot;, grade, &quot;입니다.&quot;)
</code></pre>
</li>
</ul>
</li>
<li><p><strong>짝수 합 계산기</strong></p>
<p> 사용자로부터 숫자 n을 입력받아 1부터 n까지의 짝수의 합을 계산하는 프로그램을 작성하세요.</p>
<pre><code class="language-python"> n = int(input(&quot;숫자를 입력하세요: &quot;))
 sum_even = 0
 for i in range(2, n+1, 2):
     sum_even += i
 print(&quot;1부터&quot;, n, &quot;까지의 짝수의 합은&quot;, sum_even, &quot;입니다.&quot;)
</code></pre>
</li>
<li><p><strong>BMI 계산기</strong></p>
<p> 사용자로부터 키(cm)와 몸무게(kg)를 입력받아 BMI를 계산하고 비만도를 출력하는 프로그램을 작성하세요.</p>
<ul>
<li><p>BMI = 몸무게(kg) / (키(m) * 키(m))</p>
</li>
<li><p>18.5 미만: 저체중</p>
</li>
<li><p>18.5 이상 23 미만: 정상</p>
</li>
<li><p>23 이상 25 미만: 과체중</p>
</li>
<li><p>25 이상: 비만</p>
<pre><code class="language-python">height = float(input(&quot;키를 입력하세요(cm): &quot;)) / 100  # cm를 m로 변환
weight = float(input(&quot;몸무게를 입력하세요(kg): &quot;))
bmi = weight / (height * height)
print(&quot;BMI:&quot;, bmi)
if bmi &lt; 18.5:
  print(&quot;저체중&quot;)
elif bmi &lt; 23:
  print(&quot;정상&quot;)
elif bmi &lt; 25:
  print(&quot;과체중&quot;)
else:
  print(&quot;비만&quot;)
</code></pre>
</li>
</ul>
</li>
</ol>
<h2 id="실전-대비-요약-팁">실전 대비 요약 팁</h2>
<ol>
<li><strong>변수와 자료형</strong><ul>
<li>변수 생성: <code>변수명 = 값</code></li>
<li>자료형: int, float, str</li>
<li>타입 확인: <code>type(변수명)</code></li>
</ul>
</li>
<li><strong>산술 연산자</strong><ul>
<li>기본: <code>+</code>, , , <code>/</code>, <code>//</code>, <code>%</code></li>
<li>거듭제곱: <code>*</code></li>
<li>우선순위: 괄호 &gt; 거듭제곱 &gt; 곱셈/나눗셈 &gt; 덧셈/뺄셈</li>
</ul>
</li>
<li><strong>조건문</strong><ul>
<li>기본 구조: <code>if 조건: 실행문</code></li>
<li>관계 연산자: <code>==</code>, <code>!=</code>, <code>&gt;</code>, <code>&lt;</code>, <code>&gt;=</code>, <code>&lt;=</code></li>
<li>들여쓰기로 코드 블록 구분</li>
</ul>
</li>
<li><strong>입력과 출력</strong><ul>
<li>입력: <code>input(&quot;메시지&quot;)</code></li>
<li>형변환: <code>int()</code>, <code>float()</code>, <code>str()</code></li>
<li>출력: <code>print()</code></li>
</ul>
</li>
<li><strong>주석</strong><ul>
<li>한 줄: <code>#</code></li>
<li>여러 줄: <code>&#39;&#39;&#39;</code> 또는 <code>&quot;&quot;&quot;</code></li>
</ul>
</li>
<li><strong>자주 나오는 실수</strong><ul>
<li>들여쓰기 오류: 일관된 들여쓰기 유지</li>
<li>변수명 오류: 변수명 규칙 준수</li>
<li>타입 오류: 적절한 형변환 필요</li>
<li>괄호 오류: 괄호 쌍 맞추기</li>
</ul>
</li>
<li><strong>코드 실행 팁</strong><ul>
<li>코드 실행 전 문법 오류 확인</li>
<li>테스트 케이스 활용하여 검증</li>
<li>주석 활용하여 코드 이해도 높이기</li>
</ul>
</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[C/Chapter10. 구조체]]></title>
            <link>https://velog.io/@lullaby_/CChapter10.-%EA%B5%AC%EC%A1%B0%EC%B2%B4</link>
            <guid>https://velog.io/@lullaby_/CChapter10.-%EA%B5%AC%EC%A1%B0%EC%B2%B4</guid>
            <pubDate>Wed, 01 Oct 2025 00:51:07 GMT</pubDate>
            <description><![CDATA[<h3 id="1-구조체-기본-개념">1. 구조체 기본 개념</h3>
<ul>
<li><strong>정의</strong>: 서로 다른 데이터형의 변수들을 하나로 묶어서 사용하는 기능</li>
<li><strong>목적</strong>: 사용자 정의형을 만드는 방법</li>
<li><strong>문법</strong>:</li>
</ul>
<pre><code class="language-c">struct 태그명 {
    데이터형 멤버1;
    데이터형 멤버2;
    ...
};
</code></pre>
<h3 id="2-구조체-정의와-선언">2. 구조체 정의와 선언</h3>
<pre><code class="language-c">struct content {
    char title[40];
    int price;
    double rate;
};
</code></pre>
<ul>
<li>구조체 정의는 함수 밖에서, 소스 파일 시작 부분에 정의</li>
<li><code>struct content</code>가 새로운 데이터형이 됨</li>
<li>구조체 변수 선언: <code>struct content c1;</code></li>
</ul>
<h3 id="3-구조체-초기화">3. 구조체 초기화</h3>
<pre><code class="language-c">// 방법 1: 선언과 동시에 초기화
struct content c1 = {&quot;Avengers&quot;, 11000, 8.8};

// 방법 2: 부분 초기화 (나머지는 0으로 초기화)
struct content c2 = {&quot;Movie&quot;, 5000};

// 방법 3: 구조체 변수 간 초기화
struct content c3 = c1;
</code></pre>
<h3 id="4-구조체-멤버-접근">4. 구조체 멤버 접근</h3>
<ul>
<li><strong>멤버 접근 연산자</strong>: <code>.</code> (점 연산자)</li>
<li><strong>간접 멤버 접근 연산자</strong>: <code>&gt;</code> (화살표 연산자, 포인터용)</li>
</ul>
<pre><code class="language-c">c1.price = 10000;        // 점 연산자
ptr-&gt;price = 10000;      // 화살표 연산자
</code></pre>
<h3 id="5-구조체-배열">5. 구조체 배열</h3>
<pre><code class="language-c">struct content arr[] = {
    {&quot;Movie1&quot;, 5000, 7.5},
    {&quot;Movie2&quot;, 8000, 8.0},
    {&quot;Movie3&quot;, 6000, 6.5}
};
</code></pre>
<ul>
<li>배열 원소 접근: <code>arr[i].member</code></li>
</ul>
<h3 id="6-구조체-포인터">6. 구조체 포인터</h3>
<pre><code class="language-c">struct content* ptr = &amp;c1;
ptr-&gt;price = 9000;        // 포인터를 통한 멤버 접근
(*ptr).price = 9000;      // 동일한 표현
</code></pre>
<ul>
<li><code>const</code> 포인터: 읽기 전용 접근</li>
</ul>
<h3 id="7-함수-매개변수로-구조체-전달">7. 함수 매개변수로 구조체 전달</h3>
<h3 id="값에-의한-호출-call-by-value">값에 의한 호출 (Call by Value)</h3>
<pre><code class="language-c">void print_content(struct content c);
</code></pre>
<ul>
<li>구조체 전체를 복사하여 전달</li>
<li>메모리 낭비, 시간 소모 가능</li>
</ul>
<h3 id="참조에-의한-호출-call-by-reference---권장">참조에 의한 호출 (Call by Reference) - 권장</h3>
<pre><code class="language-c">void print_content(const struct content* ptr);  // 입력용
void modify_content(struct content* ptr);       // 수정용
</code></pre>
<h3 id="8-중첩-구조체">8. 중첩 구조체</h3>
<pre><code class="language-c">struct point {
    int x, y;
};
struct line {
    struct point start, end;
};
</code></pre>
<ul>
<li>멤버의 멤버 접근: <code>ln.start.x</code></li>
</ul>
<hr>
<h2 id="🎯-예상-문제-및-풀이">🎯 예상 문제 및 풀이</h2>
<h3 id="【문제-1】-구조체-정의-및-메모리-크기-10점">【문제 1】 구조체 정의 및 메모리 크기 (10점)</h3>
<p>다음 구조체의 메모리 크기를 계산하고, 그 이유를 설명하시오.</p>
<pre><code class="language-c">struct student {
    char name[20];
    int age;
    double gpa;
};
</code></pre>
<p><strong>풀이:</strong></p>
<ul>
<li>char name[20]: 20바이트</li>
<li>int age: 4바이트</li>
<li>double gpa: 8바이트</li>
<li>총 32바이트 (20+4+8)</li>
<li>단, 메모리 정렬에 따라 실제 크기는 더 클 수 있음</li>
</ul>
<h3 id="【문제-2】-구조체-초기화-및-사용-15점">【문제 2】 구조체 초기화 및 사용 (15점)</h3>
<p>다음 코드의 출력 결과를 예측하고, 오류가 있다면 수정하시오.</p>
<pre><code class="language-c">struct book {
    char title[30];
    int pages;
    double price;
};

int main() {
    struct book b1 = {&quot;C Programming&quot;, 500};
    struct book b2;

    b2 = {&quot;Data Structure&quot;, 400, 35.5};  // 오류!

    printf(&quot;%s %d %.1f\n&quot;, b1.title, b1.pages, b1.price);
    return 0;
}
</code></pre>
<p><strong>풀이:</strong></p>
<ul>
<li>b1 초기화: price는 0.0으로 자동 초기화</li>
<li>b2 대입문 오류: 선언 후 <code>{}</code>로 직접 대입 불가</li>
<li>수정: <code>strcpy(b2.title, &quot;Data Structure&quot;); b2.pages = 400; b2.price = 35.5;</code></li>
<li>출력: <code>C Programming 500 0.0</code></li>
</ul>
<h3 id="【문제-3】-구조체-배열-검색-20점">【문제 3】 구조체 배열 검색 (20점)</h3>
<p>학생 정보를 저장하는 구조체 배열에서 특정 학생을 찾는 함수를 작성하시오.</p>
<pre><code class="language-c">struct student {
    char name[20];
    int id;
    double gpa;
};

// 학번으로 학생을 찾는 함수 (반환: 인덱스, 없으면 -1)
int find_student(const struct student arr[], int size, int target_id);
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-c">int find_student(const struct student arr[], int size, int target_id) {
    for (int i = 0; i &lt; size; i++) {
        if (arr[i].id == target_id) {
            return i;  // 찾은 학생의 인덱스 반환
        }
    }
    return -1;  // 찾지 못함
}
</code></pre>
<h3 id="【문제-4】-구조체-포인터-활용-15점">【문제 4】 구조체 포인터 활용 (15점)</h3>
<p>다음 코드의 출력 결과를 예측하시오.</p>
<pre><code class="language-c">struct point {
    int x, y;
};

int main() {
    struct point p1 = {10, 20};
    struct point* ptr = &amp;p1;

    ptr-&gt;x += 5;
    (*ptr).y *= 2;

    printf(&quot;%d %d\n&quot;, p1.x, p1.y);
    printf(&quot;%d %d\n&quot;, ptr-&gt;x, ptr-&gt;y);
    return 0;
}
</code></pre>
<p><strong>풀이:</strong></p>
<ul>
<li>ptr은 p1을 가리킴</li>
<li>ptr-&gt;x += 5: p1.x = 10 + 5 = 15</li>
<li>(*ptr).y *= 2: p1.y = 20 * 2 = 40</li>
<li>출력: <code>15 40</code> (두 번 동일)</li>
</ul>
<h3 id="【문제-5】-함수-매개변수-전달-방식-20점">【문제 5】 함수 매개변수 전달 방식 (20점)</h3>
<p>다음 두 함수의 차이점을 설명하고, 각각 언제 사용해야 하는지 서술하시오.</p>
<pre><code class="language-c">// 함수 A
void print_book1(struct book b);

// 함수 B
void print_book2(const struct book* b);
</code></pre>
<p><strong>풀이:</strong></p>
<ul>
<li><strong>함수 A (값에 의한 호출)</strong>:<ul>
<li>구조체 전체를 복사하여 전달</li>
<li>원본 데이터 안전, 메모리/시간 비효율적</li>
<li>작은 구조체에 적합</li>
</ul>
</li>
<li><strong>함수 B (참조에 의한 호출)</strong>:<ul>
<li>구조체 주소만 전달</li>
<li>메모리/시간 효율적, const로 안전성 보장</li>
<li>큰 구조체에 권장</li>
</ul>
</li>
</ul>
<h3 id="【문제-6】-중첩-구조체-15점">【문제 6】 중첩 구조체 (15점)</h3>
<p>다음 구조체에서 사각형의 넓이를 계산하는 함수를 작성하시오.</p>
<pre><code class="language-c">struct point {
    int x, y;
};

struct rectangle {
    struct point top_left;
    struct point bottom_right;
};

double calc_area(const struct rectangle* rect);
</code></pre>
<p><strong>풀이:</strong></p>
<pre><code class="language-c">double calc_area(const struct rectangle* rect) {
    int width = rect-&gt;bottom_right.x - rect-&gt;top_left.x;
    int height = rect-&gt;top_left.y - rect-&gt;bottom_right.y;
    return (double)(width * height);
}
</code></pre>
<h3 id="【문제-7】-열거체-활용-10점">【문제 7】 열거체 활용 (10점)</h3>
<p>요일을 나타내는 열거체를 정의하고, 주말인지 평일인지 판단하는 함수를 작성하시오.</p>
<p><strong>풀이:</strong></p>
<pre><code class="language-c">enum weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
};

int is_weekend(enum weekday day) {
    return (day == SATURDAY || day == SUNDAY);
}
</code></pre>
<hr>
<h2 id="💡-실전-대비-팁">💡 실전 대비 팁</h2>
<h3 id="자주-하는-실수들">자주 하는 실수들</h3>
<ol>
<li><p><strong>구조체 사용 시 <code>struct</code> 키워드 누락</strong></p>
<pre><code class="language-c"> content c1;  // 오류!
 struct content c1;  // 올바름
</code></pre>
</li>
<li><p><strong>선언 후 <code>{}</code> 직접 대입</strong></p>
<pre><code class="language-c"> struct book b;
 b = {&quot;Title&quot;, 300};  // 오류!
</code></pre>
</li>
<li><p><strong>구조체 변수 직접 비교</strong></p>
<pre><code class="language-c"> if (b1 == b2)  // 오류!
 // 멤버별로 비교해야 함
</code></pre>
</li>
<li><p><strong>배열 멤버 직접 대입</strong></p>
<pre><code class="language-c"> b1.title = b2.title;  // 오류!
 strcpy(b1.title, b2.title);  // 올바름
</code></pre>
</li>
</ol>
]]></description>
        </item>
        <item>
            <title><![CDATA[C/Chapter09. 문자열]]></title>
            <link>https://velog.io/@lullaby_/CChapter09.-%EB%AC%B8%EC%9E%90%EC%97%B4</link>
            <guid>https://velog.io/@lullaby_/CChapter09.-%EB%AC%B8%EC%9E%90%EC%97%B4</guid>
            <pubDate>Wed, 01 Oct 2025 00:50:07 GMT</pubDate>
            <description><![CDATA[<h3 id="1-문자와-문자열의-차이점">1. 문자와 문자열의 차이점</h3>
<ul>
<li><strong>문자</strong>: 하나의 문자 (<code>&#39;A&#39;</code>, <code>&#39;\n&#39;</code>) - 단일 인용부호 사용</li>
<li><strong>문자열</strong>: 연속된 문자들의 모임 (<code>&quot;hello&quot;</code>) - 이중 인용부호 사용</li>
<li><strong>널 종료 문자열</strong>: 문자열 끝에 널 문자(<code>\0</code>) 저장</li>
</ul>
<h3 id="2-문자-배열-선언-및-초기화">2. 문자 배열 선언 및 초기화</h3>
<pre><code class="language-c">char str1[10] = &quot;abc&quot;;        // 크기 10, &quot;abc&quot; + 널 문자
char str2[] = &quot;hello&quot;;        // 크기 자동 할당 (6개)
char str3[10] = &quot;&quot;;           // 모든 원소를 널 문자로 초기화
</code></pre>
<p><strong>⚠️ 중요 포인트:</strong></p>
<ul>
<li>배열 크기 = 문자열 길이 + 1 (널 문자 포함)</li>
<li>초기화 시 문자열이 배열보다 길면 오류 발생</li>
</ul>
<h3 id="3-표준-c-문자열-처리-함수-stringh">3. 표준 C 문자열 처리 함수 (<code>&lt;string.h&gt;</code>)</h3>
<table>
<thead>
<tr>
<th>함수</th>
<th>기능</th>
<th>사용법</th>
</tr>
</thead>
<tbody><tr>
<td><code>strlen()</code></td>
<td>문자열 길이 (널 문자 제외)</td>
<td><code>int len = strlen(str);</code></td>
</tr>
<tr>
<td><code>strcpy()</code></td>
<td>문자열 복사</td>
<td><code>strcpy(dest, src);</code></td>
</tr>
<tr>
<td><code>strcmp()</code></td>
<td>문자열 비교</td>
<td><code>int result = strcmp(s1, s2);</code></td>
</tr>
<tr>
<td><code>strcat()</code></td>
<td>문자열 연결</td>
<td><code>strcat(dest, src);</code></td>
</tr>
<tr>
<td><code>strchr()</code></td>
<td>문자 검색</td>
<td><code>char* p = strchr(str, &#39;c&#39;);</code></td>
</tr>
<tr>
<td><code>strstr()</code></td>
<td>문자열 검색</td>
<td><code>char* p = strstr(str, &quot;sub&quot;);</code></td>
</tr>
<tr>
<td><code>strtok()</code></td>
<td>토큰 분리</td>
<td><code>char* token = strtok(str, &quot;-&quot;);</code></td>
</tr>
<tr>
<td><img src="https://velog.velcdn.com/images/lullaby_/post/1ba01520-ae15-429f-9847-dc18459015ac/image.png" alt=""></td>
<td></td>
<td></td>
</tr>
<tr>
<td><img src="https://velog.velcdn.com/images/lullaby_/post/163cc1f3-758d-4d39-99e5-58818543bf3e/image.png" alt=""></td>
<td></td>
<td></td>
</tr>
<tr>
<td><img src="blob:https://velog.io/766ddad1-33d8-441b-b39e-63c433371277" alt="업로드중.."></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h3 id="4-문자열-포인터">4. 문자열 포인터</h3>
<pre><code class="language-c">char* p = &quot;hello&quot;;           // 문자열 리터럴을 가리킴 (읽기 전용)
const char* cp = &quot;world&quot;;    // 읽기 전용 포인터 (권장)
char str[] = &quot;test&quot;;
char* p2 = str;              // 수정 가능한 문자 배열을 가리킴
</code></pre>
<h3 id="5-2차원-문자-배열-vs-문자열-포인터-배열">5. 2차원 문자 배열 vs 문자열 포인터 배열</h3>
<pre><code class="language-c">// 2차원 문자 배열 (수정 가능)
char books[3][20] = {&quot;book1&quot;, &quot;book2&quot;, &quot;book3&quot;};

// 문자열 포인터 배열 (읽기 전용)
const char* menu[] = {&quot;File&quot;, &quot;Edit&quot;, &quot;View&quot;};
</code></pre>
<h2 id="🔥-시험-출제-포인트">🔥 시험 출제 포인트</h2>
<h3 id="1-버퍼-오버런-문제">1. 버퍼 오버런 문제</h3>
<ul>
<li><code>strcpy()</code>, <code>strcat()</code> 함수의 안전성 문제</li>
<li><code>_CRT_SECURE_NO_WARNINGS</code> 매크로 사용법</li>
<li>안전한 함수: <code>strcpy_s()</code>, <code>strcat_s()</code></li>
</ul>
<h3 id="2-문자열-비교">2. 문자열 비교</h3>
<pre><code class="language-c">// ❌ 잘못된 방법
if (str1 == str2)  // 주소 비교

// ✅ 올바른 방법
if (strcmp(str1, str2) == 0)  // 내용 비교
</code></pre>
<h3 id="3-strtok-함수-사용법외워">3. strtok() 함수 사용법//외워!!!!!!!!!!!</h3>
<pre><code class="language-c">char str[] = &quot;010-123-4567&quot;;
char* token = strtok(str, &quot;-&quot;);  // 첫 번째 토큰
while (token != NULL) {
    printf(&quot;%s\n&quot;, token);
    token = strtok(NULL, &quot;-&quot;);   // 다음 토큰
}
</code></pre>
<h2 id="📝-예상-문제--해답">📝 예상 문제 &amp; 해답</h2>
<h3 id="문제-1-기본-개념-객관식">문제 1: 기본 개념 (객관식)</h3>
<p>다음 중 올바른 문자 배열 선언은?</p>
<ol>
<li><code>char str[5] = &quot;hello&quot;;</code></li>
<li><code>char str[6] = &quot;hello&quot;;</code></li>
<li><code>char str[] = &quot;hello&quot;;</code></li>
<li>2번과 3번 모두</li>
</ol>
<p><strong>정답: 4번</strong></p>
<ul>
<li>&quot;hello&quot;는 5글자 + 널 문자 = 6바이트 필요</li>
<li>3번은 자동으로 크기 6으로 할당됨</li>
</ul>
<h3 id="문제-2-코드-분석-주관식">문제 2: 코드 분석 (주관식)</h3>
<pre><code class="language-c">#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

int main(void) {
    char str1[10] = &quot;abc&quot;;
    char str2[10] = &quot;xyz&quot;;
    char temp[10];

    strcpy(temp, str1);
    strcpy(str1, str2);
    strcpy(str2, temp);

    printf(&quot;str1: %s, str2: %s\n&quot;, str1, str2);
    return 0;
}
</code></pre>
<p><strong>출력 결과는?</strong></p>
<p><strong>정답: <code>str1: xyz, str2: abc</code></strong></p>
<ul>
<li>두 문자열을 교환하는 코드</li>
</ul>
<h3 id="문제-3-문자열-길이-주관식">문제 3: 문자열 길이 (주관식)</h3>
<pre><code class="language-c">char str[] = &quot;Hello\nWorld&quot;;
int len = strlen(str);
</code></pre>
<p>변수 <code>len</code>의 값은?</p>
<p><strong>정답: 11</strong></p>
<ul>
<li><code>\n</code>은 하나의 문자로 취급</li>
<li>널 문자는 길이에 포함되지 않음</li>
</ul>
<h3 id="문제-4-포인터와-배열-주관식">문제 4: 포인터와 배열 (주관식)</h3>
<pre><code class="language-c">char str[] = &quot;programming&quot;;
char* p = str + 3;
printf(&quot;%c\n&quot;, *p);
printf(&quot;%s\n&quot;, p);
</code></pre>
<p>출력 결과는?</p>
<p><strong>정답:</strong></p>
<pre><code>g
gramming
</code></pre><h3 id="문제-5-문자열-검색-코딩">문제 5: 문자열 검색 (코딩)</h3>
<p>다음 함수를 완성하시오. 문자열에서 특정 문자의 개수를 세는 함수이다.</p>
<pre><code class="language-c">int count_char(const char* str, char ch) {
    int count = 0;
    // 여기를 완성하시오
    return count;
}
</code></pre>
<p><strong>정답:</strong></p>
<pre><code class="language-c">int count_char(const char* str, char ch) {
    int count = 0;
    while (*str != &#39;\0&#39;) {
        if (*str == ch)
            count++;
        str++;
    }
    return count;
}
</code></pre>
<h3 id="문제-6-strtok-활용-코딩">문제 6: strtok 활용 (코딩)</h3>
<p>이메일 주소 &quot;<a href="mailto:user@domain.com">user@domain.com</a>&quot;에서 사용자명과 도메인을 분리하는 코드를 작성하시오.</p>
<p><strong>정답:</strong></p>
<pre><code class="language-c">#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

int main(void) {
    char email[] = &quot;user@domain.com&quot;;
    char* user = strtok(email, &quot;@&quot;);
    char* domain = strtok(NULL, &quot;@&quot;);

    printf(&quot;사용자명: %s\n&quot;, user);
    printf(&quot;도메인: %s\n&quot;, domain);
    return 0;
}
</code></pre>
<h2 id="🎯-실전-대비-체크리스트">🎯 실전 대비 체크리스트</h2>
<h3 id="✅-암기해야-할-것들">✅ 암기해야 할 것들</h3>
<ul>
<li><input disabled="" type="checkbox"> 주요 문자열 함수들의 반환 타입과 매개변수</li>
<li><input disabled="" type="checkbox"> <code>strcmp()</code> 함수의 반환값 (0: 같음, 양수: 첫 번째가 큰 경우, 음수: 두 번째가 큰 경우)</li>
<li><input disabled="" type="checkbox"> 문자 상수 vs 문자열 상수 표기법</li>
<li><input disabled="" type="checkbox"> 포인터 산술 연산 규칙</li>
</ul>
<h3 id="✅-실수하기-쉬운-부분">✅ 실수하기 쉬운 부분</h3>
<ul>
<li><input disabled="" type="checkbox"> 문자열 비교 시 <code>==</code> 대신 <code>strcmp()</code> 사용</li>
<li><input disabled="" type="checkbox"> 배열 크기 계산 시 널 문자 고려</li>
<li><input disabled="" type="checkbox"> <code>strtok()</code> 사용 후 원본 문자열 변경됨 주의</li>
<li><input disabled="" type="checkbox"> 문자열 리터럴은 수정 불가능</li>
</ul>
<h3 id="✅-코딩-문제-대비">✅ 코딩 문제 대비</h3>
<ul>
<li><input disabled="" type="checkbox"> 문자열 뒤집기 함수 작성</li>
<li><input disabled="" type="checkbox"> 회문(palindrome) 검사 함수</li>
<li><input disabled="" type="checkbox"> 문자열에서 공백 제거 함수</li>
<li><input disabled="" type="checkbox"> 문자열 분할 및 조합 문제</li>
</ul>
<h2 id="🔧-디버깅-팁">🔧 디버깅 팁</h2>
<ol>
<li><strong>세그멘테이션 오류 방지</strong><ul>
<li>배열 경계 확인</li>
<li>널 포인터 체크</li>
<li>문자열 끝 널 문자 확인</li>
</ul>
</li>
<li><strong>메모리 관리</strong><ul>
<li>동적 할당된 문자열의 해제</li>
<li>스택 오버플로우 방지</li>
</ul>
</li>
<li><strong>컴파일러 경고 주의</strong><ul>
<li>문자열 관련 보안 경고</li>
<li>타입 불일치 경고</li>
</ul>
</li>
</ol>
<h2 id="📖-마지막-점검-문제">📖 마지막 점검 문제</h2>
<h3 id="종합-문제-단어-카운터-프로그램">종합 문제: 단어 카운터 프로그램</h3>
<p>사용자로부터 문장을 입력받아 단어의 개수를 세는 프로그램을 작성하시오.
(단어는 공백으로 구분됨)</p>
<p><strong>해답:</strong></p>
<pre><code class="language-c">#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;ctype.h&gt;

int count_words(const char* sentence) {
    int count = 0;
    int in_word = 0;

    while (*sentence) {
        if (isspace(*sentence)) {
            in_word = 0;
        } else if (!in_word) {
            in_word = 1;
            count++;
        }
        sentence++;
    }
    return count;
}

int main(void) {
    char sentence[100];
    printf(&quot;문장을 입력하세요: &quot;);
    fgets(sentence, sizeof(sentence), stdin);

    printf(&quot;단어 개수: %d\n&quot;, count_words(sentence));
    return 0;
}
</code></pre>
]]></description>
        </item>
    </channel>
</rss>