<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>codeaddict 님의 블로그</title>
    <link>https://codeaddict.tistory.com/</link>
    <description>코드애딕트 블로그 소개

안녕하세요! 저는 컴퓨터 비전 연구자이자 프로그래밍 enthusiast인 코드애딕트입니다. 이 블로그에서는 Python, C++, PyTorch, 그리고 딥러닝 및 컴퓨터 비전 관련 다양한 주제를 다룰 예정입니다.

제가 다룰 내용은 다음과 같습니다:

Python 고급 기능: Python의 심화 기술과 라이브러리를 통해 효율적인 코드 작성법과 실용적인 팁을 공유합니다.

C++ 기초 및 심화: C++의 기초부터 고급 개념까지,</description>
    <language>ko</language>
    <pubDate>Sun, 10 May 2026 01:59:12 +0900</pubDate>
    <generator>TISTORY</generator>
    <ttl>100</ttl>
    <managingEditor>codeaddict</managingEditor>
    <item>
      <title>Python Intermediate_016_Encapsulation in Python &amp;mdash; Concepts, Examples, and Practical Application</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate016Encapsulation-in-Python-%E2%80%94-Concepts-Examples-and-Practical-Application</link>
      <description>&lt;h1 id=&quot;9367&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;1. Introduction&lt;/b&gt;&lt;/h1&gt;
&lt;p id=&quot;eff3&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Encapsulation is a cornerstone of object-oriented programming (OOP) that bundles data (attributes) and the methods that manipulate it into a single unit &amp;mdash; a class &amp;mdash; while restricting direct access to the data.&lt;/p&gt;
&lt;p id=&quot;b0bd&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Think of encapsulation as a secure vault. Inside the vault, you store sensitive items (data) and provide specific tools (methods) to interact with them. Only authorized personnel (the class&amp;rsquo;s methods) can access or modify the contents, while outsiders (external code) must use the provided interface.&lt;/p&gt;
&lt;p id=&quot;9d49&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In Python, encapsulation uses naming conventions:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;4a8a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Public:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;No prefix, accessible everywhere (e.g., data).&lt;/li&gt;
&lt;li id=&quot;fd52&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Protected:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Single underscore (_data), a hint for internal or subclass use, though not enforced.&lt;/li&gt;
&lt;li id=&quot;ea56&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Private:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Double underscore (__data), triggering name mangling to discourage direct access.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;819a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Encapsulation in Python: Public, Protected, and Private&lt;/h1&gt;
&lt;p id=&quot;2b3e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 1: Public Members &amp;mdash; Weather Data&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class WeatherStation:
    def __init__(self, temperature):
        self.temp = temperature  # Public attribute

    def report(self):
        print(f&quot;Current temperature: {self.temp}&amp;deg;C&quot;)

# Using the class
station = WeatherStation(25)
print(station.temp)  # Direct access
station.temp = -500  # Oops, unrealistic value
print(station.temp)
station.report()&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;ad67&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;25
-500
Current temperature: -500&amp;deg;C&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;ba51&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Detailed Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;4828&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;temp is public, so anyone can read or write it (station.temp = -500).&lt;/li&gt;
&lt;li id=&quot;a239&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Pros:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Simple and straightforward for small, safe scenarios.&lt;/li&gt;
&lt;li id=&quot;802b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Cons:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;No validation means temp can be set to absurd values (e.g., -500&amp;deg;C), breaking the realism of a weather system.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;22ad&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 2: Protected Members &amp;mdash; Inventory Tracker&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Inventory:
    def __init__(self, stock):
        self._stock = stock  # Protected attribute

    def check_stock(self):
        print(f&quot;Items in stock: {self._stock}&quot;)

    def restock(self, amount):
        self._stock += amount
        print(f&quot;Restocked {amount}. New stock: {self._stock}&quot;)

# Using the class
shop = Inventory(100)
print(shop._stock)  # Accessible, but discouraged
shop._stock = -10  # Can still modify, though it&amp;rsquo;s &quot;protected&quot;
print(shop._stock)
shop.check_stock()
shop.restock(50)&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;4f0e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;100
-10
Items in stock: -10
Restocked 50. New stock: 40&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;124c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Detailed Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;a4b5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;_stock with a single underscore is &amp;ldquo;protected,&amp;rdquo; signaling it&amp;rsquo;s for internal use or subclasses.&lt;/li&gt;
&lt;li id=&quot;ad66&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Python doesn&amp;rsquo;t block access (shop._stock = -10 works), but the underscore tells developers, &amp;ldquo;Hey, use the methods instead!&amp;rdquo;&lt;/li&gt;
&lt;li id=&quot;f6a8&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Pros:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Suggests a boundary, useful for teamwork or documentation.&lt;/li&gt;
&lt;li id=&quot;a9b7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Cons:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;No real protection &amp;mdash; negative stock is still possible, which doesn&amp;rsquo;t make sense for an inventory.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;2f50&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 3: Private Members &amp;mdash; Patient Records&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class PatientRecord:
    def __init__(self, name, age):
        self.__name = name  # Private attribute
        self.__age = None   # Private attribute
        self.set_age(age)   # Use setter for validation

    def get_name(self):
        return self.__name

    def get_age(self):
        return self.__age

    def set_age(self, new_age):
        if isinstance(new_age, int) and 0 &amp;lt;= new_age &amp;lt;= 120:
            self.__age = new_age
        else:
            print(f&quot;Error: Age must be an integer between 0 and 120. Keeping {self.__age}&quot;)

    def display(self):
        print(f&quot;Patient: {self.__name}, Age: {self.__age}&quot;)

# Using the class
patient = PatientRecord(&quot;Emma&quot;, 30)
print(patient.get_name())  # Access via getter
patient.set_age(35)       # Update via setter
patient.display()
patient.set_age(-5)       # Invalid age
# print(patient.__age)     # AttributeError
patient.display()&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;c480&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;subunit&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;Emma
Patient: Emma, Age: 35
Error: Age must be an integer between 0 and 120. Keeping 35
Patient: Emma, Age: 35&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;e5c3&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Detailed Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;34fc&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;__name and __age are private,, making direct access tricky (patient.__age fails).&lt;/li&gt;
&lt;li id=&quot;6ff5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;get_name, get_age, and set_age provide a controlled interface. set_age validates input, ensuring age stays realistic (0&amp;ndash;120).&lt;/li&gt;
&lt;li id=&quot;2b1d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Pros:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Protects sensitive data (like patient info) and enforces rules.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;4b19&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Why Encapsulation Matters: A Problem and Solution&lt;/h1&gt;
&lt;p id=&quot;313b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s apply encapsulation to a real-world data problem.&lt;/p&gt;
&lt;h2 id=&quot;4cdc&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Problem: Managing a Budget Tracker&lt;/h2&gt;
&lt;p id=&quot;ac10&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;You&amp;rsquo;re creating a Budget class to track expenses. Without encapsulation, users could set the budget to negative values or bypass spending limits, breaking financial logic.&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Budget:
    def __init__(self, total):
        self.total = total  # Public attribute

    def spend(self, amount):
        self.total -= amount
        print(f&quot;Spent {amount}. Remaining: {self.total}&quot;)

# Using the class
budget = Budget(1000)
print(f&quot;Initial budget: {budget.total}&quot;)
budget.spend(300)
budget.total = -500  # Direct manipulation!
print(f&quot;After tampering: {budget.total}&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;643b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;Initial budget: 1000
Spent 300. Remaining: 700
After tampering: -500&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;6831&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Issue:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c1b1&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;total is public, so it can be set to invalid values (e.g., -500), which doesn&amp;rsquo;t make sense for a budget.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;f09f&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Solution: Encapsulation with Private Members&lt;/h2&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Budget:
    def __init__(self, total):
        self.__total = None  # Private attribute
        self.set_total(total)  # Validate initial value

    def get_total(self):
        return self.__total

    def set_total(self, amount):
        if isinstance(amount, (int, float)) and amount &amp;gt;= 0:
            self.__total = amount
        else:
            print(f&quot;Error: Budget must be non-negative. Keeping {self.__total}&quot;)

    def spend(self, amount):
        if amount &amp;gt; 0 and amount &amp;lt;= self.__total:
            self.__total -= amount
            print(f&quot;Spent {amount}. Remaining: {self.__total}&quot;)
        else:
            print(f&quot;Error: Invalid spend amount or insufficient funds&quot;)

# Using the class
budget = Budget(1000)
print(f&quot;Initial budget: {budget.get_total()}&quot;)
budget.spend(300)
budget.set_total(-500)  # Invalid attempt
# budget.__total = 2000   # AttributeError
budget.spend(200)
print(f&quot;Final budget: {budget.get_total()}&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;00bd&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;subunit&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;Initial budget: 1000
Spent 300. Remaining: 700
Error: Budget must be non-negative. Keeping 700
Spent 200. Remaining: 500
Final budget: 500&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;668f&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation of the Solution:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;4b10&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;__total is private, preventing direct changes (budget.__total = 2000 fails).&lt;/li&gt;
&lt;li id=&quot;3ad2&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;set_total ensures the budget stays non-negative, and spend checks for valid withdrawals.&lt;/li&gt;
&lt;li id=&quot;a0eb&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;get_total provides read-only access, keeping the interface clean.&lt;/li&gt;
&lt;li id=&quot;4b89&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Benefit:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;The budget stays logical and secure, avoiding negative or inconsistent states.&lt;/li&gt;
&lt;/ul&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>Encapsulation</category>
      <category>encapsulation python</category>
      <category>private attribute</category>
      <category>protected attribute</category>
      <category>public attribute</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/64</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate016Encapsulation-in-Python-%E2%80%94-Concepts-Examples-and-Practical-Application#entry64comment</comments>
      <pubDate>Sat, 5 Apr 2025 21:36:28 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_015_ Sorting with .sort() and Lambda in Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate015-Sorting-with-sort-and-Lambda-in-Python</link>
      <description>&lt;p id=&quot;cd8f&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Sorting is a fundamental operation in programming, and Python provides the .sort() method to make it easy to sort lists in place. When combined with the key parameter and lambda functions, .sort() becomes a powerful tool for custom sorting. In this tutorial, we&amp;rsquo;ll explore the traditional approach to sorting, introduce the .sort() method with lambda, and provide examples to solidify your understanding.&lt;/p&gt;
&lt;h1 id=&quot;9d72&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;What is .sort() with Lambda?&lt;/h1&gt;
&lt;p id=&quot;cbd1&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The .sort() method modifies a list in place, arranging its elements in a specified order (ascending by default). The key parameter allows you to define a custom sorting criterion, and a lambda function provides a concise way to specify that criterion without defining a separate function.&lt;/p&gt;
&lt;h2 id=&quot;90d6&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Syntax:&lt;/h2&gt;
&lt;pre class=&quot;maxima&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;list.sort(key=lambda x: expression)&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;ab79&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;.sort(): Sorts the list in place.&lt;/li&gt;
&lt;li id=&quot;fcbf&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;key=: Specifies the sorting rule.&lt;/li&gt;
&lt;li id=&quot;77eb&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;lambda x: expression: An anonymous function where x is each list element, and expression defines what to sort by.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;b47f&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Examples of Sorting with .sort() and Lambda&lt;/h1&gt;
&lt;h2 id=&quot;1126&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 1: Sorting a List of Strings Alphabetically&lt;/h2&gt;
&lt;p id=&quot;2476&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Using a basic .sort():&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;routeros&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;fruits = [&quot;banana&quot;, &quot;apple&quot;, &quot;cherry&quot;]
fruits.sort()  # Default alphabetical sort
print(fruits)
# Output: ['apple', 'banana', 'cherry']&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;5f28&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Using .sort() with lambda:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;sas&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;fruits = [&quot;banana&quot;, &quot;apple&quot;, &quot;cherry&quot;]
fruits.sort(key=lambda x: x[0])  # Sort by the first character
print(fruits)
# Output: ['apple', 'banana', 'cherry']&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;45aa&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In this case, sorting by the first character (x[0]) gives the same result as the default sort, but it demonstrates how lambda works.&lt;/p&gt;
&lt;h2 id=&quot;646e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 2: Sorting a List of Tuples by the Second Element&lt;/h2&gt;
&lt;p id=&quot;fe81&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Using a for loop (traditional approach):&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;sas&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;fruits = [(&quot;banana&quot;, 3), (&quot;apple&quot;, 2), (&quot;cherry&quot;, 5)]
sorted_fruits = sorted(fruits, key=lambda x: x[1])  # Note: sorted() creates a new list
print(sorted_fruits)
# Output: [('apple', 2), ('banana', 3), ('cherry', 5)]&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;7ff2&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Using .sort() with lambda:&lt;/b&gt;&lt;/p&gt;
&lt;p id=&quot;94ce&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;fruits = [(&quot;banana&quot;, 3), (&quot;apple&quot;, 2), (&quot;cherry&quot;, 5)] fruits.sort(key=lambda x: x[1])&lt;span&gt;&amp;nbsp;&lt;/span&gt;# Sort by the second element (number)&lt;span&gt;&amp;nbsp;&lt;/span&gt;print(fruits)&lt;span&gt;&amp;nbsp;&lt;/span&gt;# Output: [('apple', 2), ('banana', 3), ('cherry', 5)]&lt;/p&gt;
&lt;p id=&quot;32fa&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here, .sort() modifies the original list, sorting by the second element of each tuple (x[1]).&lt;/p&gt;
&lt;h2 id=&quot;4af6&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 3: Sorting Strings by Length&lt;/h2&gt;
&lt;p id=&quot;f97e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Using a basic .sort():&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;routeros&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;words = [&quot;cat&quot;, &quot;elephant&quot;, &quot;dog&quot;]
words.sort()  # Default alphabetical sort
print(words)
# Output: ['cat', 'dog', 'elephant']&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;56c4&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Using .sort() with lambda:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;sas&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;words = [&quot;cat&quot;, &quot;elephant&quot;, &quot;dog&quot;]
words.sort(key=lambda x: len(x))  # Sort by string length
print(words)
# Output: ['cat', 'dog', 'elephant']&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;4d63&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The lambda function len(x) sorts the list based on the length of each string.&lt;/p&gt;
&lt;h2 id=&quot;dbe4&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 4: Sorting a List of Tuples by Multiple Criteria&lt;/h2&gt;
&lt;p id=&quot;2ade&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Using .sort() with lambda:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;sas&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;items = [(&quot;apple&quot;, 2), (&quot;banana&quot;, 1), (&quot;apple&quot;, 1)]
items.sort(key=lambda x: (x[0], x[1]))  # Sort by fruit name, then number
print(items)
# Output: [('apple', 1), ('apple', 2), ('banana', 1)]&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;cee3&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here, the lambda returns a tuple (x[0], x[1]), sorting first by the fruit name and then by the number when names are identical.&lt;/p&gt;
&lt;h2 id=&quot;60d0&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 5: Sorting in Descending Order&lt;/h2&gt;
&lt;p id=&quot;02f7&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Using .sort() with lambda and reverse:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;numbers = [3, 1, 4, 1, 5]
numbers.sort(key=lambda x: x, reverse=True)  # Sort in descending order
print(numbers)
# Output: [5, 4, 3, 1, 1]&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;a16a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The reverse=True parameter flips the sort order, and the lambda x: x sorts based on the elements themselves.&lt;/p&gt;
&lt;h1 id=&quot;2ccc&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;When to Use .sort() with Lambda&lt;/h1&gt;
&lt;p id=&quot;160e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Use .sort() with lambda when:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;3332&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;You need to sort a list in place based on a custom criterion.&lt;/li&gt;
&lt;li id=&quot;bb7e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;You want concise, readable code for simple sorting logic.&lt;/li&gt;
&lt;li id=&quot;550c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The list contains complex elements like tuples or objects.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;48eb&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Do not use .sort() with lambda when:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;cfe5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;You need a new sorted list without modifying the original (use sorted() instead).&lt;/li&gt;
&lt;li id=&quot;2d6d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The sorting logic is too complex for a single lambda expression.&lt;/li&gt;
&lt;/ul&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>python intermediate</category>
      <category>Sort</category>
      <category>sort python programming</category>
      <category>sorted python</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/63</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate015-Sorting-with-sort-and-Lambda-in-Python#entry63comment</comments>
      <pubDate>Sat, 5 Apr 2025 21:34:47 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_014: Understanding @staticmethod in Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate014-Understanding-staticmethod-in-Python</link>
      <description>&lt;p id=&quot;de20&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In the previous lesson, we covered&lt;span&gt;&amp;nbsp;&lt;/span&gt;@classmethod.&amp;nbsp;&amp;nbsp;&lt;/p&gt;
&lt;p id=&quot;9513&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In this tutorial, we will focus on&lt;span&gt;&amp;nbsp;&lt;/span&gt;@staticmethod&lt;span&gt;&amp;nbsp;&lt;/span&gt;and understand its role in Python. Static methods do not operate on an instance or the class itself, making them useful for utility functions that logically belong to a class but do not need access to instance or class attributes.&lt;/p&gt;
&lt;h1 id=&quot;3abe&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. Regular Methods: Attached to the Class&lt;/h1&gt;
&lt;p id=&quot;3685&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Regular methods are glued to the class or its instances. Check this out:&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Car:
    def __init__(self, model):
        self.model = model

    def describe(self):  # Regular method
        return f&quot;This is a {self.model}&quot;

# Using it
my_car = Car(&quot;Toyota&quot;)
description = my_car.describe()  # This is a Toyota&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;ea6c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Flow and Connection:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;bbd7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;describe needs self &amp;mdash; it&amp;rsquo;s attached to the instance (my_car). It grabs self.model to build the string.&lt;/li&gt;
&lt;li id=&quot;2a25&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Without an instance, this doesn&amp;rsquo;t work &amp;mdash; you can&amp;rsquo;t call Car.describe() directly. It&amp;rsquo;s tied to the object&amp;rsquo;s state.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;e183&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Static Methods vs. Standalone Functions&lt;/h1&gt;
&lt;p id=&quot;1c76&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Now, let&amp;rsquo;s meet @staticmethod. It lives in the class but doesn&amp;rsquo;t need its data. To prove it&amp;rsquo;s not truly &amp;ldquo;attached,&amp;rdquo; I&amp;rsquo;ll pair it with an identical standalone function:&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;# Standalone function
def honk_sound():
    return &quot;Beep beep!&quot;

class Car:
    def __init__(self, model):
        self.model = model

    def describe(self):
        return f&quot;This is a {self.model}&quot;

    @staticmethod
    def honk_sound():  # Static method
        return &quot;Beep beep!&quot;

# Using both
standalone_result = honk_sound()      # Beep beep!
static_result = Car.honk_sound()      # Beep beep!
car_instance = Car(&quot;Toyota&quot;)
instance_result = car_instance.honk_sound()  # Beep beep!&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;161d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Flow and Comparison:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;bdc9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Standalone&lt;span&gt;&amp;nbsp;&lt;/span&gt;honk_sound:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;A plain function, not tied to any class. Call it anywhere with honk_sound(), and it returns &amp;ldquo;Beep beep!&amp;rdquo; &amp;mdash; no Car needed.&lt;/li&gt;
&lt;li id=&quot;49f7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Static&lt;span&gt;&amp;nbsp;&lt;/span&gt;honk_sound:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Lives inside Car, called with Car.honk_sound() or even car_instance.honk_sound(). It still returns &amp;ldquo;Beep beep!&amp;rdquo; but doesn&amp;rsquo;t use self or any Car data.&lt;/li&gt;
&lt;li id=&quot;2972&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Key Point:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Both do the&lt;span&gt;&amp;nbsp;&lt;/span&gt;exact same thing. The static version isn&amp;rsquo;t attached to the class&amp;rsquo;s state &amp;mdash; it&amp;rsquo;s just parked there. The Car. prefix is Python&amp;rsquo;s way of organizing it, not a sign of dependency.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;4874&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Practical Example: Numbers, No Class Strings Attached&lt;/h1&gt;
&lt;p id=&quot;d109&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s try a number-based example. Regular methods use class data; static methods and standalone functions don&amp;rsquo;t:&lt;/p&gt;
&lt;pre class=&quot;oxygene&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;# Standalone function
def square(n):
    return n * n

class NumberCruncher:
    def __init__(self, offset):
        self.offset = offset

    def add_offset(self, x):  # Regular method
        return x + self.offset

    @staticmethod
    def square(n):  # Static method
        return n * n

# Using them
cruncher = NumberCruncher(3)
offset_result = cruncher.add_offset(5)  # 8 (5 + 3)
static_result = NumberCruncher.square(4)  # 16 (4 * 4)
standalone_result = square(4)  # 16 (4 * 4)&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;e0ef&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Flow and Comparison:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e130&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;add_offset: Needs self.offset (3), so it&amp;rsquo;s attached &amp;mdash; adds 3 to 5, giving 8.&lt;/li&gt;
&lt;li id=&quot;cbbc&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;square (static): Takes n (4), returns 4 * 4 = 16. No self, no class data &amp;mdash; just pure math.&lt;/li&gt;
&lt;li id=&quot;d5f8&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;square (standalone): Same as the static version, called without a class. Both are identical in behavior.&lt;/li&gt;
&lt;li id=&quot;a36d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Difference:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;add_offset relies on the instance&amp;rsquo;s offset, while both squares are free of NumberCruncher&amp;rsquo;s state.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;3af2&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. Another example&lt;/h1&gt;
&lt;p id=&quot;1d0a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a practical case &amp;mdash; cleaning text. Watch how the static method mirrors a standalone function:&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;# Standalone function
def strip_spaces(text):
    return text.replace(&quot; &quot;, &quot;&quot;)

class TextCleaner:
    def __init__(self, signature):
        self.signature = signature

    def sign(self, text):  # Regular method
        return f&quot;{text} - {self.signature}&quot;

    @staticmethod
    def strip_spaces(text):  # Static method
        return text.replace(&quot; &quot;, &quot;&quot;)

# Using them
cleaner = TextCleaner(&quot;ByMe&quot;)
signed = cleaner.sign(&quot;Hello World&quot;)      # Hello World - ByMe
static_clean = TextCleaner.strip_spaces(&quot;Hi There&quot;)  # HiThere
standalone_clean = strip_spaces(&quot;Hi There&quot;)  # HiThere&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;b2ef&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Flow and Comparison:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;628b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;sign: Uses self.signature to append &amp;ldquo;ByMe&amp;rdquo; &amp;mdash; it&amp;rsquo;s attached to the instance.&lt;/li&gt;
&lt;li id=&quot;e856&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;strip_spaces (static): Takes text, removes spaces, returns &amp;ldquo;HiThere&amp;rdquo;. No self, no class connection.&lt;/li&gt;
&lt;li id=&quot;da81&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;strip_spaces (standalone): Does the same, called directly. Both are interchangeable.&lt;/li&gt;
&lt;li id=&quot;6718&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Difference:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;sign needs the instance&amp;rsquo;s signature, while strip_spaces doesn&amp;rsquo;t care about TextCleaner.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;23c0&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;5. So, Why @staticmethod?&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;d098&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Regular Methods:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Attached &amp;mdash; use them when you need instance data (self) or class data (via @classmethod with cls).&lt;/li&gt;
&lt;li id=&quot;cf1b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Static Methods:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Not attached &amp;mdash; use them for utilities that don&amp;rsquo;t need class state. They&amp;rsquo;re like standalone functions, just stored in the class for organization.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;11a3&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Why ClassName.method() Then?&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Python sticks static methods in the class&amp;rsquo;s namespace. You&lt;span&gt;&amp;nbsp;&lt;/span&gt;could&lt;span&gt;&amp;nbsp;&lt;/span&gt;write them as standalone functions, but grouping them (e.g., TextCleaner.strip_spaces) keeps your code tidy and related tools together.&lt;/p&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>class method</category>
      <category>python advanced</category>
      <category>staticmethod</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/62</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate014-Understanding-staticmethod-in-Python#entry62comment</comments>
      <pubDate>Sat, 5 Apr 2025 21:33:43 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_013: Understanding @classmethod in Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate013-Understanding-classmethod-in-Python</link>
      <description>&lt;p id=&quot;94b5&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In this lesson, we&amp;rsquo;ll learn about @classmethod . The @classmethod decorator is a neat feature in Python that lets you define methods tied to a class itself, not just its instances.&lt;/p&gt;
&lt;p id=&quot;6a0d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;if you don&amp;rsquo;t know decorators yet, I have a lesson in&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;a style=&quot;color: #000000;&quot; href=&quot;https://medium.com/@codeaddict/python-intermediate-006-decorators-in-python&quot;&gt;Python Intermediate_006: Decorators in Python&lt;/a&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(&lt;a href=&quot;https://medium.com/@staytechrich/python-intermediate-006-decorators-in-python-c7c7aaac7c8b&quot;&gt;https://medium.com/@staytechrich/python-intermediate-006-decorators-in-python-c7c7aaac7c8b&lt;/a&gt;) that&amp;rsquo;ll help you out. Let&amp;rsquo;s get started with some easy examples!&lt;/p&gt;
&lt;h1 id=&quot;1ee6&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. Basic @classmethod Example&lt;/h1&gt;
&lt;p id=&quot;d90d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a simple class method that greets you from the class level, not an instance:&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Greeter:
    message = &quot;Hello from the class!&quot;

    @classmethod
    def say_hello(cls):
        print(&quot;1. Inside class method: Accessing class data&quot;)
        return cls.message

print(&quot;START&quot;)
result = Greeter.say_hello()
print(f&quot;RESULT: {result}&quot;)
print(&quot;END&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;7293&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;oxygene&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;START
1. Inside class method: Accessing class data
RESULT: Hello from the class!
END&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;58a6&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Order of Execution&lt;/h2&gt;
&lt;p id=&quot;1c25&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s break it down step-by-step:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;7e69&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;@classmethod &amp;mdash; Marks say_hello as a class method, passing cls (the class) instead of self.&lt;/li&gt;
&lt;li id=&quot;e1a6&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(&amp;ldquo;START&amp;rdquo;) &amp;mdash; Prints &amp;ldquo;START&amp;rdquo; before the call.&lt;/li&gt;
&lt;li id=&quot;3478&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;result = Greeter.say_hello() &amp;mdash; Calls the class method directly on Greeter.&lt;/li&gt;
&lt;li id=&quot;0570&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(&amp;ldquo;1. Inside class method&amp;hellip;&amp;rdquo;) &amp;mdash; Runs inside say_hello, showing it&amp;rsquo;s active.&lt;/li&gt;
&lt;li id=&quot;89db&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;return cls.message &amp;mdash; Returns the class variable message (&amp;ldquo;Hello from the class!&amp;rdquo;).&lt;/li&gt;
&lt;li id=&quot;c25b&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(f&amp;rdquo;RESULT: {result}&amp;rdquo;) &amp;mdash; Prints the returned value.&lt;/li&gt;
&lt;li id=&quot;60f3&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(&amp;ldquo;END&amp;rdquo;) &amp;mdash; Prints &amp;ldquo;END&amp;rdquo;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p id=&quot;542e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;This is like a decorator wrapping a function, but here it shifts the focus to the class itself!&lt;/p&gt;
&lt;h1 id=&quot;5eaf&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Practical Example: Instance Tracker&lt;/h1&gt;
&lt;p id=&quot;643b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Now, let&amp;rsquo;s get practical. Imagine a class that tracks how many instances it&amp;rsquo;s created &amp;mdash; perfect for debugging or stats. We&amp;rsquo;ll use @classmethod to report it.&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class InstanceTracker:
    count = 0

    def __init__(self):
        InstanceTracker.count += 1  # Bump count when an instance is made

    @classmethod
    def get_count(cls):
        print(&quot;1. Inside class method: Checking instance count&quot;)
        return f&quot;Total instances: {cls.count}&quot;

# Test it
print(&quot;START&quot;)
t1 = InstanceTracker()
t2 = InstanceTracker()
result = InstanceTracker.get_count()
print(f&quot;RESULT: {result}&quot;)
print(&quot;END&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;5c9c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;START
1. Inside class method: Checking instance count
RESULT: Total instances: 2
END&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;7e20&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Order of Execution (for the full test)&lt;/h2&gt;
&lt;ol style=&quot;list-style-type: decimal; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;29ef&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(&amp;ldquo;START&amp;rdquo;) &amp;mdash; Prints &amp;ldquo;START&amp;rdquo; before anything happens.&lt;/li&gt;
&lt;li id=&quot;f90d&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;t1 = InstanceTracker() &amp;mdash; Creates the first instance, __init__ runs, count becomes 1.&lt;/li&gt;
&lt;li id=&quot;a222&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;t2 = InstanceTracker() &amp;mdash; Creates the second instance, count becomes 2.&lt;/li&gt;
&lt;li id=&quot;c01b&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;result = InstanceTracker.get_count() &amp;mdash; Calls the class method.&lt;/li&gt;
&lt;li id=&quot;7a74&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(&amp;ldquo;1. Inside class method&amp;hellip;&amp;rdquo;) &amp;mdash; Runs inside get_count, showing it&amp;rsquo;s working.&lt;/li&gt;
&lt;li id=&quot;cdd1&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;return f&amp;rdquo;Total instances: {cls.count}&amp;rdquo; &amp;mdash; Returns &amp;ldquo;Total instances: 2&amp;rdquo; using cls.count.&lt;/li&gt;
&lt;li id=&quot;1e7d&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(f&amp;rdquo;RESULT: {result}&amp;rdquo;) &amp;mdash; Prints the result.&lt;/li&gt;
&lt;li id=&quot;c27c&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(&amp;ldquo;END&amp;rdquo;) &amp;mdash; Prints &amp;ldquo;END&amp;rdquo;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p id=&quot;3715&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;For an instance call (e.g., t1.get_count()), it works the same way &amp;mdash; cls still refers to InstanceTracker!&lt;/p&gt;
&lt;h1 id=&quot;c1b0&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Why @classmethod Rocks&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;a28c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Class-Level Power&lt;/b&gt;: Access shared data (like count) without needing an instance.&lt;/li&gt;
&lt;li id=&quot;7240&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Factory Vibes&lt;/b&gt;: Use it for alternative constructors (more on that below).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;f60a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Bonus Example: Factory Method&lt;/h2&gt;
&lt;p id=&quot;a8d6&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a quick factory method using @classmethod, like a mini-decorator trick:&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_string(cls, data):
        print(&quot;1. Inside class method: Parsing string&quot;)
        name, age = data.split(&quot;-&quot;)
        return cls(name, int(age))

print(&quot;START&quot;)
p = Person.from_string(&quot;Alice-30&quot;)
print(f&quot;RESULT: {p.name}, {p.age}&quot;)
print(&quot;END&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;0f6a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;oxygene&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;START
1. Inside class method: Parsing string
RESULT: Alice, 30
END&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;d057&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Explanation Step by Step&lt;/h1&gt;
&lt;h2 id=&quot;31a8&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;1. What&amp;rsquo;s Happening When You Call Person.from_string(&amp;ldquo;Alice-30&amp;rdquo;)?&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;76b5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Normally, to make a Person object, you&amp;rsquo;d write something like person1 = Person(&amp;ldquo;Alice&amp;rdquo;, 30). This calls the class directly with two arguments (name and age).&lt;/li&gt;
&lt;li id=&quot;a8e0&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;But here, we&amp;rsquo;re using Person.from_string(&amp;ldquo;Alice-30&amp;rdquo;). This calls the @classmethod from_string instead of making the object right away. It&amp;rsquo;s a different way to create a Person.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;4779&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;2. Inside from_string(cls, data)&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;753f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The @classmethod decorator changes how this method works. Instead of getting self (which is for instances), it gets cls, which stands for the class itself &amp;mdash; in this case, Person.&lt;/li&gt;
&lt;li id=&quot;0b5b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;data is the input you give when you call it. Here, data is the string &amp;ldquo;Alice-30&amp;rdquo;.&lt;/li&gt;
&lt;li id=&quot;0c62&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The method&amp;rsquo;s job is to take that string, break it apart, and use it to make a Person object.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;b2e1&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;3. What data Does in from_string&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;3fe4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Inside from_string, data is the string &amp;ldquo;Alice-30&amp;rdquo; because that&amp;rsquo;s what we passed when we called Person.from_string(&amp;ldquo;Alice-30&amp;rdquo;).&lt;/li&gt;
&lt;li id=&quot;26e2&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The line name, age = data.split(&amp;ldquo;-&amp;rdquo;) takes that string and splits it at the &amp;mdash; into two parts:&lt;/li&gt;
&lt;li id=&quot;3b73&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&amp;ldquo;Alice-30&amp;rdquo; &amp;rarr; [&amp;ldquo;Alice&amp;rdquo;, &amp;ldquo;30&amp;rdquo;]&lt;/li&gt;
&lt;li id=&quot;cdba&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Then, name gets &amp;ldquo;Alice&amp;rdquo;, and age gets &amp;ldquo;30&amp;rdquo;.&lt;/li&gt;
&lt;li id=&quot;25a9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;int(age) turns the string &amp;ldquo;30&amp;rdquo; into the number 30 because age in __init__ expects a number, not a string.&lt;/li&gt;
&lt;li id=&quot;2e7b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Finally, cls(name, int(age)) is like saying Person(&amp;ldquo;Alice&amp;rdquo;, 30) &amp;mdash; it creates a new Person object using the class (cls) and returns it.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;ff32&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;4. How It All Comes Together&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;d568&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;p = Person.from_string(&amp;ldquo;Alice-30&amp;rdquo;) calls the class method.&lt;/li&gt;
&lt;li id=&quot;6667&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;data starts as &amp;ldquo;Alice-30&amp;rdquo;, gets split into name = &amp;ldquo;Alice&amp;rdquo; and age = &amp;ldquo;30&amp;rdquo;, and then makes a Person object with those values.&lt;/li&gt;
&lt;li id=&quot;e972&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;p becomes a Person object with p.name = &amp;ldquo;Alice&amp;rdquo; and p.age = 30.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;9d57&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Wrap-Up&lt;/h1&gt;
&lt;p id=&quot;a991&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Try practicing more with InstanceTracker to log creation times or extend Person with more parsing options. Happy Coding!!&lt;/p&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>class method</category>
      <category>classes and objects</category>
      <category>decorators</category>
      <category>oop python</category>
      <category>python advanced</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/61</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate013-Understanding-classmethod-in-Python#entry61comment</comments>
      <pubDate>Sat, 5 Apr 2025 21:32:33 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_012:Python&amp;rsquo;s Magic Methods in Classes(Overview)</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate012Python%E2%80%99s-Magic-Methods-in-ClassesOverview</link>
      <description>&lt;p id=&quot;c6c3&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;If you&amp;rsquo;ve been playing with Python classes, you might&amp;rsquo;ve heard of &amp;ldquo;magic methods&amp;rdquo; &amp;mdash; those special methods with double underscores (like __init__). They&amp;rsquo;re not as mysterious as they sound &amp;mdash; they just let you customize how your objects behave. In this post, we&amp;rsquo;ll cover what they are, why they matter, and give a quick peek at some common ones. Next time, we&amp;rsquo;ll dig into each one deeper. Let&amp;rsquo;s get started!&lt;/p&gt;
&lt;h1 id=&quot;f02e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. What Are Magic Methods?&lt;/h1&gt;
&lt;p id=&quot;cbe3&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Magic methods (or &amp;ldquo;dunder&amp;rdquo; methods, short for &amp;ldquo;double underscore&amp;rdquo;) are built-in Python methods you can define in your classes. They control how objects work with Python&amp;rsquo;s operators, functions, and features &amp;mdash; like addition, printing, or comparisons. You don&amp;rsquo;t call them directly; Python does it behind the scenes.&lt;/p&gt;
&lt;p id=&quot;b115&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;For example:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;da10&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;__init__ sets up a new object.&lt;/li&gt;
&lt;li id=&quot;66dd&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;__str__ decides what print() shows.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;d2d9&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;They&amp;rsquo;re &amp;ldquo;magic&amp;rdquo; because they hook into Python&amp;rsquo;s core behavior, letting you tweak it without extra code.&lt;/p&gt;
&lt;h1 id=&quot;55ab&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Why Use Them?&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;7248&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Customization&lt;/b&gt;: Make objects act how you want (e.g., adding two objects with +).&lt;/li&gt;
&lt;li id=&quot;7672&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Readability&lt;/b&gt;: Control what shows up when you print an object.&lt;/li&gt;
&lt;li id=&quot;edbf&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Power&lt;/b&gt;: Tap into Python&amp;rsquo;s built-in tools (like len() or ==) for your classes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;13ad&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;They&amp;rsquo;re optional &amp;mdash; if you don&amp;rsquo;t define them, Python uses defaults. But adding them makes your classes more useful.&lt;/p&gt;
&lt;h1 id=&quot;c889&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. A Quick Tour of Common Magic Methods&lt;/h1&gt;
&lt;p id=&quot;76b9&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a rundown of some key ones. We&amp;rsquo;ll keep it simple &amp;mdash; just what they do and a basic example. Full details come in the next lesson!&lt;/p&gt;
&lt;h2 id=&quot;4c1d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;__init__(self, &amp;hellip;)&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;bae7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;What It Does&lt;/b&gt;: Runs when you create a new object. Sets up initial values.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;2bea&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;gml&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(3, 4)  # __init__ sets x=3, y=4&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;fba2&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;__str__(self)&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;bd9e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;What It Does&lt;/b&gt;: Defines what print() shows for your object.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;1e40&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Point:
    def __str__(self):
        return f&quot;Point({self.x}, {self.y})&quot;

p = Point(3, 4)
print(p)  # Outputs: Point(3, 4)&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;92ae&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;__add__(self, other)&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;03b1&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;What It Does&lt;/b&gt;: Lets you use + to add two objects.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;76d4&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;reasonml&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Point:
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2  # p3 is Point(4, 6)&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;84b7&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;__eq__(self, other)&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;a0ae&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;What It Does&lt;/b&gt;: Decides if two objects are equal with ==.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;4621&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;gml&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Point:
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)  # True&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;d3dd&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;__len__(self)&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;9d5b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;What It Does&lt;/b&gt;: Lets len() work on your object.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;bc54&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Bag:
    def __init__(self, items):
        self.items = items
    def __len__(self):
        return len(self.items)

b = Bag([1, 2, 3])
print(len(b))  # 3&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;7cbe&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. How They Fit Together&lt;/h1&gt;
&lt;p id=&quot;9f7a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a tiny class using a few at once:&lt;/p&gt;
&lt;pre class=&quot;gml&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Point:
    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 Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3)  # Outputs: (4, 6)&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;7092&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;5. What&amp;rsquo;s Next?&lt;/h1&gt;
&lt;p id=&quot;6cba&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;This is just the start &amp;mdash; Python has a bunch of magic methods to explore. They&amp;rsquo;re called&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;dunder methods&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;because of the double underscores (__) around their names. &amp;ldquo;Dunder&amp;rdquo; is shorthand for &amp;ldquo;double under&amp;rdquo; &amp;mdash; a nickname Python folks use since they&amp;rsquo;re special methods tied to how Python works under the hood.&lt;/p&gt;
&lt;h2 id=&quot;ce18&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Why the Double Underscores?&lt;/h2&gt;
&lt;p id=&quot;1b63&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;You might wonder: why __len__ instead of just len? The double underscores mark these as reserved names &amp;mdash; Python&amp;rsquo;s way of saying, &amp;ldquo;Hey, these are mine, but you can customize them.&amp;rdquo; They&amp;rsquo;re like hooks built into the language. When you write len(obj), Python doesn&amp;rsquo;t call a plain len method &amp;mdash; it looks for __len__ in your class and runs that. The __ keeps them separate from your own method names (like calculate or show), avoiding clashes.&lt;/p&gt;
&lt;h2 id=&quot;452b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;How Do You Use Them?&lt;/h2&gt;
&lt;p id=&quot;ae4c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;You define them in your class with the exact name (like def __len__(self):), add self as the first argument (since they&amp;rsquo;re class methods), and tell Python what to do. Python calls them automatically when you use the matching feature:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;73dd&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;obj + other &amp;rarr; __add__&lt;/li&gt;
&lt;li id=&quot;ccdb&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;print(obj) &amp;rarr; __str__&lt;/li&gt;
&lt;li id=&quot;0600&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;len(obj) &amp;rarr; __len__&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;1733&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Why Not Just len?&lt;/h2&gt;
&lt;p id=&quot;5bfd&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;If it was just len, it&amp;rsquo;d conflict with the built-in len() function &amp;mdash; or any method you might name len for something else. The __len__ name is a contract: Python knows to look for it when len() is called, and you get to decide what &amp;ldquo;length&amp;rdquo; means for your object. It&amp;rsquo;s about giving you control while keeping things organized.&lt;/p&gt;
&lt;h2 id=&quot;743c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;The Big List&lt;/h2&gt;
&lt;p id=&quot;7c0a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a rundown of the most important dunder methods:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;3aff&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__init__(self, &amp;hellip;)&lt;/b&gt;: Creates a new object.&lt;/li&gt;
&lt;li id=&quot;96e7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__str__(self)&lt;/b&gt;: Controls print() output.&lt;/li&gt;
&lt;li id=&quot;2f8a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__repr__(self)&lt;/b&gt;: Gives a detailed string for debugging.&lt;/li&gt;
&lt;li id=&quot;f36a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__add__(self, other)&lt;/b&gt;: Handles +.&lt;/li&gt;
&lt;li id=&quot;5623&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__sub__(self, other)&lt;/b&gt;: Handles -.&lt;/li&gt;
&lt;li id=&quot;5500&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__mul__(self, other)&lt;/b&gt;: Handles *.&lt;/li&gt;
&lt;li id=&quot;70e4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__truediv__(self, other)&lt;/b&gt;: Handles /.&lt;/li&gt;
&lt;li id=&quot;1e12&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__eq__(self, other)&lt;/b&gt;: Checks ==.&lt;/li&gt;
&lt;li id=&quot;4513&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__lt__(self, other)&lt;/b&gt;: Checks &amp;lt;.&lt;/li&gt;
&lt;li id=&quot;e6f1&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__gt__(self, other)&lt;/b&gt;: Checks &amp;gt;.&lt;/li&gt;
&lt;li id=&quot;32e9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__le__(self, other)&lt;/b&gt;: Checks &amp;lt;=.&lt;/li&gt;
&lt;li id=&quot;2e47&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__ge__(self, other)&lt;/b&gt;: Checks &amp;gt;=.&lt;/li&gt;
&lt;li id=&quot;4cb3&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__ne__(self, other)&lt;/b&gt;: Checks !=.&lt;/li&gt;
&lt;li id=&quot;a40c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__len__(self)&lt;/b&gt;: Works with len().&lt;/li&gt;
&lt;li id=&quot;ed29&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__getitem__(self, key)&lt;/b&gt;: Enables obj[key].&lt;/li&gt;
&lt;li id=&quot;08ea&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__setitem__(self, key, value)&lt;/b&gt;: Enables obj[key] = value.&lt;/li&gt;
&lt;li id=&quot;b603&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__del__(self)&lt;/b&gt;: Runs when an object is deleted.&lt;/li&gt;
&lt;li id=&quot;1461&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;__call__(self, &amp;hellip;)&lt;/b&gt;: Lets you call an object like a function.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;1ea0&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Each one ties to a specific Python feature, and the __ makes them distinct. In the next tutorials, I&amp;rsquo;ll break down the most important ones &amp;mdash; like __init__, __str__, __add__, and __len__ &amp;mdash; with examples and tips. For now, try adding a couple to your own class and see what you can make happen!&lt;/p&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>double under</category>
      <category>dunder methods</category>
      <category>magic methods</category>
      <category>Object Oriented</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/60</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate012Python%E2%80%99s-Magic-Methods-in-ClassesOverview#entry60comment</comments>
      <pubDate>Sat, 5 Apr 2025 21:31:14 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_011: Recursive Functions in Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate011-Recursive-Functions-in-Python</link>
      <description>&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p id=&quot;8edc&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Recursive functions are a powerful programming concept where a function calls itself to solve a problem by breaking it into smaller, similar subproblems. In this tutorial, we&amp;rsquo;ll explore recursion in depth, starting with the basics and moving on to more complex problems.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;010f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. What Are Recursive Functions?&lt;/h1&gt;
&lt;p id=&quot;c30f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;A recursive function solves a problem by calling itself with a modified input, reducing the problem size until it reaches a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;base case&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;mdash; a condition that stops the recursion. It consists of two key parts:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;b09e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Base Case&lt;/b&gt;: The condition that stops the recursion.&lt;/li&gt;
&lt;li id=&quot;5e9c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Recursive Case&lt;/b&gt;: The part where the function calls itself with a smaller or simpler input.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;8347&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Think of recursion like a stack of tasks: each call adds a layer, and the base case starts resolving them backward.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;ec70&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Simple Example: Factorial of a Number&lt;/h1&gt;
&lt;p id=&quot;54c1&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The factorial of a number n (denoted as&lt;span&gt;&amp;nbsp;&lt;/span&gt;n!) is the product of all positive integers up to n. For example, 4!=4&amp;times;3&amp;times;2&amp;times;1=24.&lt;/p&gt;
&lt;p id=&quot;9d04&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a recursive function to calculate the factorial:&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def factorial(n):
    if n == 1:  # Base case
        return 1
    else:  # Recursive case
        return n * factorial(n - 1)

print(factorial(4))  # Output: 24&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;e8e8&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;How It Works:&lt;/h2&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;5949&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;factorial(4)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;4 * factorial(3)&lt;/li&gt;
&lt;li id=&quot;1c7c&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;factorial(3)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;3 * factorial(2)&lt;/li&gt;
&lt;li id=&quot;94cb&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;factorial(2)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;2 * factorial(1)&lt;/li&gt;
&lt;li id=&quot;df11&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;factorial(1)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;1&lt;span&gt;&amp;nbsp;&lt;/span&gt;(base case hit)&lt;/li&gt;
&lt;/ol&gt;
&lt;p id=&quot;a3d7&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Then, the results are computed back up:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;4361&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2&amp;times;1=2&lt;/li&gt;
&lt;li id=&quot;369a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;3&amp;times;2=6&lt;/li&gt;
&lt;li id=&quot;3bc0&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;4&amp;times;6=24&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;4c58&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Why Use Recursion?&lt;/h1&gt;
&lt;p id=&quot;366f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Recursion is ideal for problems with natural hierarchical or repetitive structures, such as:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;98c8&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Calculating factorials or Fibonacci numbers.&lt;/li&gt;
&lt;li id=&quot;4038&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Traversing trees or graphs (e.g., file directories).&lt;/li&gt;
&lt;li id=&quot;803e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Solving puzzles like the Tower of Hanoi.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;63d3&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;However, recursion can be memory-intensive due to the call stack, and it may not always be the most efficient solution.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;fdcc&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. More Complex Example: Fibonacci Sequence&lt;/h1&gt;
&lt;p id=&quot;f09b&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones (e.g., 0,1,1,2,3,5,8,&amp;hellip;0,1,1,2,3,5,8,&amp;hellip;). Here&amp;rsquo;s a recursive implementation:&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def fibonacci(n):
    if n &amp;lt;= 1:  # Base case
        return n
    else:  # Recursive case
        return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(5))  # Output: 5&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;2441&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;How It Works:&lt;/h2&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;e60b&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;fibonacci(5)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;fibonacci(4) + fibonacci(3)&lt;/li&gt;
&lt;li id=&quot;1586&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;fibonacci(4)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;fibonacci(3) + fibonacci(2)&lt;/li&gt;
&lt;li id=&quot;b2d4&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;fibonacci(3)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;fibonacci(2) + fibonacci(1)&lt;/li&gt;
&lt;li id=&quot;c993&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;fibonacci(2)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;fibonacci(1) + fibonacci(0)&lt;/li&gt;
&lt;li id=&quot;1da0&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;fibonacci(1)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;1&lt;span&gt;&amp;nbsp;&lt;/span&gt;(base case)&lt;/li&gt;
&lt;li id=&quot;28e3&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;fibonacci(0)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;0&lt;span&gt;&amp;nbsp;&lt;/span&gt;(base case)&lt;/li&gt;
&lt;/ol&gt;
&lt;p id=&quot;13c8&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The results are summed back up to compute the final value.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;bf2c&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;5. Problem 1: Power of a Number&lt;/h1&gt;
&lt;p id=&quot;89b7&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Problem&lt;/b&gt;: Write a recursive function to calculate the power of a number, e.g., 2&amp;sup3;=8.&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def power(base, exp):
    if exp == 0:  # Base case
        return 1
    else:  # Recursive case
        return base * power(base, exp - 1)

print(power(2, 3))  # Output: 8&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;febb&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Explanation:&lt;/h2&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;e749&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;power(2, 3)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;2 * power(2, 2)&lt;/li&gt;
&lt;li id=&quot;4fd2&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;power(2, 2)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;2 * power(2, 1)&lt;/li&gt;
&lt;li id=&quot;e64d&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;power(2, 1)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;2 * power(2, 0)&lt;/li&gt;
&lt;li id=&quot;c9a5&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;power(2, 0)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr;&lt;span&gt;&amp;nbsp;&lt;/span&gt;1&lt;span&gt;&amp;nbsp;&lt;/span&gt;(base case)&lt;/li&gt;
&lt;/ol&gt;
&lt;p id=&quot;f049&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Then, the results are computed back up:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;a888&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2&amp;times;1=2&lt;/li&gt;
&lt;li id=&quot;0615&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2&amp;times;2=4&lt;/li&gt;
&lt;li id=&quot;bbbc&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2&amp;times;4=8&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;bb85&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;6. Problem 2: Binary Search Using Recursion&lt;/h1&gt;
&lt;p id=&quot;ac1a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Problem&lt;/b&gt;: Implement a recursive binary search algorithm to find an element in a sorted list.&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def binary_search(arr, target, low, high):
    if low &amp;gt; high:  # Base case: element not found
        return -1
    mid = (low + high) // 2
    if arr[mid] == target:  # Base case: element found
        return mid
    elif arr[mid] &amp;gt; target:  # Search in the left half
        return binary_search(arr, target, low, mid - 1)
    else:  # Search in the right half
        return binary_search(arr, target, mid + 1, high)

arr = [1, 3, 5, 7, 9, 11]
target = 7
result = binary_search(arr, target, 0, len(arr) - 1)
print(f&quot;Element found at index: {result}&quot;)  # Output: 3&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;ad6a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Explanation:&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;11a7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The function checks the middle element of the array.&lt;/li&gt;
&lt;li id=&quot;c029&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;If the middle element is the target, it returns the index.&lt;/li&gt;
&lt;li id=&quot;61f7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;If the target is smaller, it searches the left half; if larger, it searches the right half.&lt;/li&gt;
&lt;li id=&quot;6de5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The process repeats until the target is found or the search space is exhausted.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;bf28&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;7. Problem 3: Recursive List Sum&lt;/h1&gt;
&lt;p id=&quot;c004&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Problem&lt;/b&gt;: Write a recursive function to calculate the sum of all elements in a list.&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def list_sum(arr):
    if not arr:  # Base case: empty list
        return 0
    else:  # Recursive case
        return arr[0] + list_sum(arr[1:])

arr = [1, 2, 3, 4, 5]
print(list_sum(arr))  # Output: 15&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;28ac&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Explanation:&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;1a4c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The function adds the first element of the list to the sum of the remaining elements.&lt;/li&gt;
&lt;li id=&quot;fa79&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The process repeats until the list is empty.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;8e60&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&amp;mdash; Key Takeaways&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;6b53&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Recursion is a powerful tool for solving problems that can be broken into smaller, similar subproblems.&lt;/li&gt;
&lt;li id=&quot;43ee&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Always define a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;base case&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;to stop the recursion.&lt;/li&gt;
&lt;li id=&quot;f768&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Recursion can be memory-intensive, so use it judiciously.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>binary search</category>
      <category>factorial</category>
      <category>fibonacci python</category>
      <category>REC</category>
      <category>recursive functions</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/59</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate011-Recursive-Functions-in-Python#entry59comment</comments>
      <pubDate>Sat, 5 Apr 2025 21:30:02 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_010: Inheritance in Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate010-Inheritance-in-Python</link>
      <description>&lt;p id=&quot;d653&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Inheritance is a powerful concept in&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;Object-Oriented Programming (OOP)&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;that allows a class (called a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;child class&lt;/b&gt;) to inherit attributes and methods from another class (called a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;parent class&lt;/b&gt;). This promotes&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;code reusability&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;and makes it easier to create and maintain complex programs. In this tutorial, we&amp;rsquo;ll cover inheritance with practical examples. We&amp;rsquo;ll also explain the role of&lt;span&gt;&amp;nbsp;&lt;/span&gt;super()&lt;span&gt;&amp;nbsp;&lt;/span&gt;in inheritance.&lt;/p&gt;
&lt;h1 id=&quot;d501&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. What is&lt;span&gt;&amp;nbsp;&lt;/span&gt;super()?&lt;/h1&gt;
&lt;p id=&quot;2cb0&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The&lt;span&gt;&amp;nbsp;&lt;/span&gt;super()&lt;span&gt;&amp;nbsp;&lt;/span&gt;function is used to&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;call a method from the parent class&lt;/b&gt;. It is commonly used in the&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method of a child class to ensure that the parent class&amp;rsquo;s&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method is called. This is important when the child class adds new attributes but still needs to initialize the attributes inherited from the parent class.&lt;/p&gt;
&lt;h1 id=&quot;18ee&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Key Points About&lt;span&gt;&amp;nbsp;&lt;/span&gt;super()&lt;/h1&gt;
&lt;ol style=&quot;list-style-type: decimal; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;9309&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Purpose&lt;/b&gt;: To call a method (usually&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__) from the parent class.&lt;/li&gt;
&lt;li id=&quot;8045&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;When to Use&lt;/b&gt;: When the child class has its own&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method and needs to initialize inherited attributes.&lt;/li&gt;
&lt;li id=&quot;b112&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;How It Works&lt;/b&gt;:&lt;span&gt;&amp;nbsp;&lt;/span&gt;super().__init__(...)&lt;span&gt;&amp;nbsp;&lt;/span&gt;calls the parent class&amp;rsquo;s&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method.&lt;/li&gt;
&lt;/ol&gt;
&lt;h1 id=&quot;aa79&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Example_1: Modeling Shapes with Inheritance&lt;/h1&gt;
&lt;p id=&quot;c539&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s start with a practical example where we model shapes. The parent class&lt;span&gt;&amp;nbsp;&lt;/span&gt;Shape&lt;span&gt;&amp;nbsp;&lt;/span&gt;provides a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;color attribute&lt;/b&gt;, and the child classes&lt;span&gt;&amp;nbsp;&lt;/span&gt;Rectangle&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;Circle&lt;span&gt;&amp;nbsp;&lt;/span&gt;use or modify it while calculating areas.&lt;/p&gt;
&lt;h1 id=&quot;645c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Parent Class:&lt;span&gt;&amp;nbsp;&lt;/span&gt;Shape&lt;/h1&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Shape:
    def __init__(self, color):
        self.color = color  # Inherited property
    
    def area(self):
        return 0  # Default area for a generic shape
    
    def describe(self):
        return f&quot;This is a {self.color} shape with area {self.area()}&quot;&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;bb54&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Child Class:&lt;span&gt;&amp;nbsp;&lt;/span&gt;Rectangle&lt;/h1&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Rectangle(Shape):
    def __init__(self, color, length, width):
        super().__init__(color)  # Inherit color from Shape,  Call parent's __init__ to initialize color
        self.length = length
        self.width = width
    
    def area(self):  # Override parent's area method
        return self.length * self.width
    
    def change_color(self, new_color):  # Modify inherited color
        self.color = new_color
        return f&quot;Rectangle color changed to {self.color}&quot;&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;420d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Child Class:&lt;span&gt;&amp;nbsp;&lt;/span&gt;Circle&lt;/h1&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Circle(Shape):
    def __init__(self, color, radius):
        super().__init__(color)  # Inherit color from Shape
        self.radius = radius
    
    def area(self):  # Override parent's area method
        return 3.14 * self.radius * self.radius
    
    def describe(self):  # Override parent's describe method
        return f&quot;This is a {self.color} circle with area {self.area():.2f}&quot;&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;4837&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Using the Classes&lt;/h1&gt;
&lt;pre class=&quot;routeros&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;# Create objects with numbers
rect = Rectangle(&quot;Blue&quot;, 4, 5)
circ = Circle(&quot;Red&quot;, 3)

# Test using inherited color and numeric calculations
print(rect.describe())          # Output: This is a Blue shape with area 20
print(rect.change_color(&quot;Green&quot;))  # Output: Rectangle color changed to Green
print(rect.describe())          # Output: This is a Green shape with area 20
print(circ.describe())          # Output: This is a Red circle with area 28.26&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;228b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Explanation of the Shape Example&lt;/h1&gt;
&lt;p id=&quot;52bb&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Parent Class (&lt;/b&gt;&lt;b&gt;Shape&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;71cc&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Defines a&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;attribute that is inherited by child classes.&lt;/li&gt;
&lt;li id=&quot;a0dd&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Provides a default&lt;span&gt;&amp;nbsp;&lt;/span&gt;area&lt;span&gt;&amp;nbsp;&lt;/span&gt;method (returns&lt;span&gt;&amp;nbsp;&lt;/span&gt;0&lt;span&gt;&amp;nbsp;&lt;/span&gt;for a generic shape).&lt;/li&gt;
&lt;li id=&quot;b570&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Has a&lt;span&gt;&amp;nbsp;&lt;/span&gt;describe&lt;span&gt;&amp;nbsp;&lt;/span&gt;method that uses the inherited&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;area.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;f40c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Child Class (&lt;/b&gt;&lt;b&gt;Rectangle&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c082&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Inherits&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;and uses it in the&lt;span&gt;&amp;nbsp;&lt;/span&gt;describe&lt;span&gt;&amp;nbsp;&lt;/span&gt;method.&lt;/li&gt;
&lt;li id=&quot;9b34&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Adds&lt;span&gt;&amp;nbsp;&lt;/span&gt;length&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;width&lt;span&gt;&amp;nbsp;&lt;/span&gt;attributes to calculate the area (length * width).&lt;/li&gt;
&lt;li id=&quot;72e1&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Uses&lt;span&gt;&amp;nbsp;&lt;/span&gt;super().__init__(color)&lt;span&gt;&amp;nbsp;&lt;/span&gt;to initialize the inherited&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;attribute.&lt;/li&gt;
&lt;li id=&quot;2ab0&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Includes a&lt;span&gt;&amp;nbsp;&lt;/span&gt;change_color&lt;span&gt;&amp;nbsp;&lt;/span&gt;method to modify the inherited&lt;span&gt;&amp;nbsp;&lt;/span&gt;color.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;2d0d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Child Class (&lt;/b&gt;&lt;b&gt;Circle&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;614b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Inherits&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;and uses it in an overridden&lt;span&gt;&amp;nbsp;&lt;/span&gt;describe&lt;span&gt;&amp;nbsp;&lt;/span&gt;method.&lt;/li&gt;
&lt;li id=&quot;b572&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Adds a&lt;span&gt;&amp;nbsp;&lt;/span&gt;radius&lt;span&gt;&amp;nbsp;&lt;/span&gt;attribute to calculate the area (3.14 * radius * radius).&lt;/li&gt;
&lt;li id=&quot;ef2d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Uses&lt;span&gt;&amp;nbsp;&lt;/span&gt;super().__init__(color)&lt;span&gt;&amp;nbsp;&lt;/span&gt;to initialize the inherited&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;attribute.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;06f2&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Numeric Breakdown&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;f8ce&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Rectangle:&lt;span&gt;&amp;nbsp;&lt;/span&gt;length = 4,&lt;span&gt;&amp;nbsp;&lt;/span&gt;width = 5&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr; Area =&lt;span&gt;&amp;nbsp;&lt;/span&gt;4 * 5 = 20.&lt;/li&gt;
&lt;li id=&quot;8a3e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Circle:&lt;span&gt;&amp;nbsp;&lt;/span&gt;radius = 3&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;rarr; Area =&lt;span&gt;&amp;nbsp;&lt;/span&gt;3.14 * 3 * 3 = 28.26.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;4f4d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Role of&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/b&gt;&lt;b&gt;super()&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c5ef&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;In both&lt;span&gt;&amp;nbsp;&lt;/span&gt;Rectangle&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;Circle,&lt;span&gt;&amp;nbsp;&lt;/span&gt;super().__init__(color)&lt;span&gt;&amp;nbsp;&lt;/span&gt;ensures that the&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;attribute is initialized by the&lt;span&gt;&amp;nbsp;&lt;/span&gt;Shape&lt;span&gt;&amp;nbsp;&lt;/span&gt;class.&lt;/li&gt;
&lt;li id=&quot;7984&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Without&lt;span&gt;&amp;nbsp;&lt;/span&gt;super(), the&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;attribute would not be initialized, and the program would throw an error.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;5edb&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Example_2: Inheritance with Numeric Calculations&lt;/h1&gt;
&lt;p id=&quot;f938&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Now, let&amp;rsquo;s explore another example involving&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;numeric calculations&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;to further solidify your understanding of inheritance and&lt;span&gt;&amp;nbsp;&lt;/span&gt;super().&lt;/p&gt;
&lt;h1 id=&quot;fca3&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Parent Class:&lt;span&gt;&amp;nbsp;&lt;/span&gt;Calculator&lt;/h1&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class Calculator:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def add(self):
        return self.a + self.b

    def subtract(self):
        return self.a - self.b&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;65b8&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Child Class:&lt;span&gt;&amp;nbsp;&lt;/span&gt;AdvancedCalculator&lt;/h1&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class AdvancedCalculator(Calculator):
    def multiply(self):
        return self.a * self.b

    def divide(self):
        if self.b != 0:
            return self.a / self.b
        else:
            return &quot;Division by zero is not allowed!&quot;&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;05b1&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Using the Classes&lt;/h1&gt;
&lt;pre class=&quot;routeros&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;# Create an instance of AdvancedCalculator
calc = AdvancedCalculator(10, 5)

# Use methods from both parent and child classes
print(&quot;Addition:&quot;, calc.add())          # Output: Addition: 15
print(&quot;Subtraction:&quot;, calc.subtract())  # Output: Subtraction: 5
print(&quot;Multiplication:&quot;, calc.multiply())  # Output: Multiplication: 50
print(&quot;Division:&quot;, calc.divide())       # Output: Division: 2.0&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;d90d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Explanation of the Calculator Example&lt;/h1&gt;
&lt;p id=&quot;362d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Parent Class (&lt;/b&gt;&lt;b&gt;Calculator&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;09e0&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Defines basic arithmetic operations (add&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;subtract).&lt;/li&gt;
&lt;li id=&quot;8a31&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Initializes two numbers (a&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;b).&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;97ef&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Child Class (&lt;/b&gt;&lt;b&gt;AdvancedCalculator&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;de82&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Inherits&lt;span&gt;&amp;nbsp;&lt;/span&gt;add&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;subtract&lt;span&gt;&amp;nbsp;&lt;/span&gt;methods from&lt;span&gt;&amp;nbsp;&lt;/span&gt;Calculator.&lt;/li&gt;
&lt;li id=&quot;61df&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Adds advanced operations like&lt;span&gt;&amp;nbsp;&lt;/span&gt;multiply&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;divide.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;c9e4&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;- Why&lt;span&gt;&amp;nbsp;&lt;/span&gt;super()&lt;span&gt;&amp;nbsp;&lt;/span&gt;Wasn&amp;rsquo;t Used in&lt;span&gt;&amp;nbsp;&lt;/span&gt;AdvancedCalculator&lt;/h1&gt;
&lt;p id=&quot;3ccb&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In the&lt;span&gt;&amp;nbsp;&lt;/span&gt;AdvancedCalculator&lt;span&gt;&amp;nbsp;&lt;/span&gt;class, we didn&amp;rsquo;t use&lt;span&gt;&amp;nbsp;&lt;/span&gt;super()&lt;span&gt;&amp;nbsp;&lt;/span&gt;because the parent class (Calculator) already initializes the attributes&lt;span&gt;&amp;nbsp;&lt;/span&gt;a&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;b&lt;span&gt;&amp;nbsp;&lt;/span&gt;in its&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method. When the&lt;span&gt;&amp;nbsp;&lt;/span&gt;AdvancedCalculator&lt;span&gt;&amp;nbsp;&lt;/span&gt;class inherits from&lt;span&gt;&amp;nbsp;&lt;/span&gt;Calculator, it automatically gains access to all the attributes and methods of the parent class, including&lt;span&gt;&amp;nbsp;&lt;/span&gt;a&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;b.&lt;/p&gt;
&lt;h1 id=&quot;8bf1&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;- Key Difference Between the Two Examples&lt;/h1&gt;
&lt;h1 id=&quot;b29b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;&amp;mdash; Example 1:&lt;span&gt;&amp;nbsp;&lt;/span&gt;Rectangle&lt;span&gt;&amp;nbsp;&lt;/span&gt;Class&lt;/h1&gt;
&lt;p id=&quot;f075&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In the&lt;span&gt;&amp;nbsp;&lt;/span&gt;Rectangle&lt;span&gt;&amp;nbsp;&lt;/span&gt;class, we&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;added new attributes&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(length&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;width) in addition to inheriting the&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;attribute from the&lt;span&gt;&amp;nbsp;&lt;/span&gt;Shape&lt;span&gt;&amp;nbsp;&lt;/span&gt;class. Since the child class (Rectangle) has its own&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method, we need to explicitly call the parent class&amp;rsquo;s&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method using&lt;span&gt;&amp;nbsp;&lt;/span&gt;super()&lt;span&gt;&amp;nbsp;&lt;/span&gt;to initialize the inherited&lt;span&gt;&amp;nbsp;&lt;/span&gt;color&lt;span&gt;&amp;nbsp;&lt;/span&gt;attribute.&lt;/p&gt;
&lt;h1 id=&quot;a515&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;&amp;mdash; Example 2:&lt;span&gt;&amp;nbsp;&lt;/span&gt;AdvancedCalculator&lt;span&gt;&amp;nbsp;&lt;/span&gt;Class&lt;/h1&gt;
&lt;p id=&quot;5a0c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In the&lt;span&gt;&amp;nbsp;&lt;/span&gt;AdvancedCalculator&lt;span&gt;&amp;nbsp;&lt;/span&gt;class, we&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;did not add any new attributes&lt;/b&gt;. It simply inherits the&lt;span&gt;&amp;nbsp;&lt;/span&gt;a&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;b&lt;span&gt;&amp;nbsp;&lt;/span&gt;attributes from the&lt;span&gt;&amp;nbsp;&lt;/span&gt;Calculator&lt;span&gt;&amp;nbsp;&lt;/span&gt;class. Since the child class (AdvancedCalculator) doesn&amp;rsquo;t have its own&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method, Python automatically calls the parent class&amp;rsquo;s&lt;span&gt;&amp;nbsp;&lt;/span&gt;__init__&lt;span&gt;&amp;nbsp;&lt;/span&gt;method to initialize&lt;span&gt;&amp;nbsp;&lt;/span&gt;a&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;b.&lt;/p&gt;
&lt;h1 id=&quot;1529&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. Challenge for Readers&lt;/h1&gt;
&lt;p id=&quot;881b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Problem:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Create a&lt;span&gt;&amp;nbsp;&lt;/span&gt;BankAccount&lt;span&gt;&amp;nbsp;&lt;/span&gt;class with attributes&lt;span&gt;&amp;nbsp;&lt;/span&gt;account_number&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;balance. Then, create a&lt;span&gt;&amp;nbsp;&lt;/span&gt;SavingsAccount&lt;span&gt;&amp;nbsp;&lt;/span&gt;class that inherits from&lt;span&gt;&amp;nbsp;&lt;/span&gt;BankAccount&lt;span&gt;&amp;nbsp;&lt;/span&gt;and adds an attribute&lt;span&gt;&amp;nbsp;&lt;/span&gt;interest_rate. Finally, create a&lt;span&gt;&amp;nbsp;&lt;/span&gt;FixedDeposit&lt;span&gt;&amp;nbsp;&lt;/span&gt;class that inherits from&lt;span&gt;&amp;nbsp;&lt;/span&gt;BankAccount&lt;span&gt;&amp;nbsp;&lt;/span&gt;and adds an attribute&lt;span&gt;&amp;nbsp;&lt;/span&gt;duration.&lt;/p&gt;
&lt;p id=&quot;b908&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.balance = balance

    def display_balance(self):
        return f&quot;Account {self.account_number} has a balance of ${self.balance}.&quot;

class SavingsAccount(BankAccount):
    def __init__(self, account_number, balance, interest_rate):
        super().__init__(account_number, balance)  # Call parent's __init__
        self.interest_rate = interest_rate  # Add new attribute

    def calculate_interest(self):
        return self.balance * self.interest_rate / 100

class FixedDeposit(BankAccount):
    def __init__(self, account_number, balance, duration):
        super().__init__(account_number, balance)  # Call parent's __init__
        self.duration = duration  # Add new attribute

    def display_duration(self):
        return f&quot;Fixed Deposit Account {self.account_number} has a duration of {self.duration} months.&quot;

# Example usage
savings = SavingsAccount(&quot;SA123&quot;, 1000, 5)
fixed_deposit = FixedDeposit(&quot;FD456&quot;, 5000, 12)

print(savings.display_balance())  # Output: Account SA123 has a balance of $1000.
print(&quot;Interest:&quot;, savings.calculate_interest())  # Output: Interest: 50.0
print(fixed_deposit.display_balance())  # Output: Account FD456 has a balance of $5000.
print(fixed_deposit.display_duration())  # Output: Fixed Deposit Account FD456 has a duration of 12 months.&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;e43b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;By practicing these examples, you&amp;rsquo;ll gain a solid understanding of inheritance in Python.&lt;/p&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>class</category>
      <category>class inheritance</category>
      <category>inheritance</category>
      <category>python advanced</category>
      <category>super in python</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/58</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate010-Inheritance-in-Python#entry58comment</comments>
      <pubDate>Sat, 5 Apr 2025 21:28:20 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_009: Lambda Functions in Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate009-Lambda-Functions-in-Python</link>
      <description>&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p id=&quot;aaf9&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Lambda functions, also known as&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;anonymous functions&lt;/b&gt;, are a concise way to create small, throwaway functions in Python. They are often used for short, simple operations that are not reused elsewhere in the code. In this tutorial, we&amp;rsquo;ll cover the syntax of lambda functions, compare them with regular functions, provide examples, and solve problems using both approaches.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;67f3&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. Syntax of Lambda Functions&lt;/h1&gt;
&lt;p id=&quot;1068&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The syntax for a lambda function is:&lt;/p&gt;
&lt;pre class=&quot;vim&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;lambda arguments: expression&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;cf87&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;lambda&lt;/b&gt;: The keyword used to define a lambda function.&lt;/li&gt;
&lt;li id=&quot;1b7b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;arguments&lt;/b&gt;: The input parameters (similar to a regular function).&lt;/li&gt;
&lt;li id=&quot;4afc&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;expression&lt;/b&gt;: A single expression that is evaluated and returned. Lambda functions can only contain one expression.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;cdf4&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Examples: Lambda vs Regular Functions&lt;/h1&gt;
&lt;h2 id=&quot;5fba&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 1: Adding Two Numbers&lt;/h2&gt;
&lt;p id=&quot;d4bd&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Lambda Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;routeros&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;add = lambda x, y: x + y
print(add(3, 5))  # Output: 8&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;c17d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Regular Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;sas&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def add(x, y):
    return x + y
print(add(3, 5))  # Output: 8&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;1a7a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c117&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The lambda function is a one-liner and doesn&amp;rsquo;t require a&lt;span&gt;&amp;nbsp;&lt;/span&gt;def&lt;span&gt;&amp;nbsp;&lt;/span&gt;statement or a function name.&lt;/li&gt;
&lt;li id=&quot;25c5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The regular function is more readable and reusable for larger tasks.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;d364&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 2: Multiplying Two Numbers&lt;/h2&gt;
&lt;p id=&quot;5827&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Lambda Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;gml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;multiply = lambda x, y: x * y
print(multiply(4, 5))  # Output: 20&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;4087&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Regular Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def multiply(x, y):
    return x * y

print(multiply(4, 5))  # Output: 20&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;d1ec&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 3: Checking if a Number is Even&lt;/h2&gt;
&lt;p id=&quot;7d67&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Lambda Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;sas&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;is_even = lambda x: x % 2 == 0
print(is_even(4))  # Output: True
print(is_even(5))  # Output: False&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;d64a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Regular Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;sas&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def is_even(x):
    return x % 2 == 0
print(is_even(4))  # Output: True
print(is_even(5))  # Output: False&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;2a32&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 4: Concatenating Strings&lt;/h2&gt;
&lt;p id=&quot;a576&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Lambda Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;mipsasm&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;concat = lambda s1, s2: s1 + &quot; &quot; + s2
print(concat(&quot;Hello&quot;, &quot;World&quot;))  # Output: Hello World&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;a3ba&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Regular Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def concat(s1, s2):
    return s1 + &quot; &quot; + s2
print(concat(&quot;Hello&quot;, &quot;World&quot;))  # Output: Hello World&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;2e4e&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Problems and Solutions&lt;/h1&gt;
&lt;h2 id=&quot;1de8&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Problem 1: Square a Number&lt;/h2&gt;
&lt;p id=&quot;64fe&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Task:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Write a program to square a number.&lt;/p&gt;
&lt;p id=&quot;e62c&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution with Lambda:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;square = lambda x: x**2
print(square(5))  # Output: 25&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;6564&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution with Regular Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def square(x):
    return x**2

print(square(5))  # Output: 25&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;4084&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Problem 2: Check if a Number is Positive&lt;/h2&gt;
&lt;p id=&quot;741d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Task:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Write a program to check if a number is positive.&lt;/p&gt;
&lt;p id=&quot;dd98&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution with Lambda:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;gauss&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;is_positive = lambda x: x &amp;gt; 0
print(is_positive(10))  # Output: True
print(is_positive(-5))  # Output: False&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;10a7&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution with Regular Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;python&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def is_positive(x):
    return x &amp;gt; 0
print(is_positive(10))  # Output: True
print(is_positive(-5))  # Output: False&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;33d3&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Problem 3: Calculate the Area of a Rectangle&lt;/h2&gt;
&lt;p id=&quot;18d2&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Task:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Write a program to calculate the area of a rectangle.&lt;/p&gt;
&lt;p id=&quot;e599&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution with Lambda:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;hsp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;area = lambda length, width: length * width
print(area(10, 5))  # Output: 50&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;0de6&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution with Regular Function:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;hsp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;def area(length, width):
    return length * width

print(area(10, 5))  # Output: 50&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;5ac9&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. When to Use Lambda vs Regular Functions&lt;/h1&gt;
&lt;p id=&quot;111d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Use Lambda When:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;0dcb&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The function is short and simple.&lt;/li&gt;
&lt;li id=&quot;1fd9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The function is used only once (throwaway).&lt;/li&gt;
&lt;li id=&quot;bfeb&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;You need a quick function for simple operations.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;3d62&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Use Regular Functions When:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;f5e5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The function is complex or has multiple statements.&lt;/li&gt;
&lt;li id=&quot;1da4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The function is reused multiple times.&lt;/li&gt;
&lt;li id=&quot;912b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;You need better readability and documentation.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>lambda function</category>
      <category>lambda functions in python</category>
      <category>python beginner</category>
      <category>python programming lambda function</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/57</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate009-Lambda-Functions-in-Python#entry57comment</comments>
      <pubDate>Sat, 5 Apr 2025 21:26:59 +0900</pubDate>
    </item>
    <item>
      <title>cpp_021: Const Modifier in C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp021-Const-Modifier-in-C</link>
      <description>&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p id=&quot;2cbe&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In C++, the const keyword is a powerful tool for controlling how data is used in your program. It allows you to declare variables, parameters, or return values as &amp;ldquo;constant,&amp;rdquo; meaning they cannot be modified after initialization. This is crucial for writing safe, predictable code &amp;mdash; especially when passing data to functions. In this post, we&amp;rsquo;ll explore const in a general sense, using examples with variables, arrays, and function interactions to show how it enforces read-only behavior and what happens when we mix const and non-const contexts.&lt;/p&gt;
&lt;h1 id=&quot;12ee&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. Basics of const with Variables&lt;/h1&gt;
&lt;p id=&quot;dd59&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s start simple. The const keyword makes a variable immutable after it&amp;rsquo;s initialized.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    const int x = 5; // x is constant
    // x = 10; // Error: assignment of read-only variable 'x'
    cout &amp;lt;&amp;lt; &quot;x = &quot; &amp;lt;&amp;lt; x &amp;lt;&amp;lt; endl;

    int y = 20; // y is not constant
    y = 30; // Perfectly fine
    cout &amp;lt;&amp;lt; &quot;y = &quot; &amp;lt;&amp;lt; y &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;3b9c&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;ini&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;x = 5
y = 30&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;044e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Key Point:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;const int x can&amp;rsquo;t be changed after initialization, but y (non-const) can. This is the foundation of const: it locks a value in place. This highlights the purpose of&lt;span&gt;&amp;nbsp;&lt;/span&gt;const: it locks a value in place to prevent changes. If you attempt to modify&lt;span&gt;&amp;nbsp;&lt;/span&gt;x, the compiler will throw an error, as shown in the commented line within the code.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;4d94&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Using const in Function Parameters&lt;/h1&gt;
&lt;p id=&quot;3db9&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;When you pass data to a function, const ensures the function can&amp;rsquo;t modify it. Let&amp;rsquo;s see this with a scalar (single value) and then an array.&lt;/p&gt;
&lt;h2 id=&quot;cf10&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 1: Scalar Parameter&lt;/h2&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

void printValue(const int x) {
    // x = 50; // Error: assignment of read-only parameter 'x'
    cout &amp;lt;&amp;lt; &quot;Inside function, x = &quot; &amp;lt;&amp;lt; x &amp;lt;&amp;lt; endl;
}

int main() {
    int a = 10;
    printValue(a); // Pass a to the function
    a = 20; // Change a outside the function
    cout &amp;lt;&amp;lt; &quot;Outside function, a = &quot; &amp;lt;&amp;lt; a &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;84f3&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;fortran&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Inside function, x = 10
Outside function, a = 20&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;3a63&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;What&amp;rsquo;s Happening?&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;2760&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;const int x is a copy of a. The function can&amp;rsquo;t modify x, but since it&amp;rsquo;s a copy, the original a isn&amp;rsquo;t affected anyway.&lt;/li&gt;
&lt;li id=&quot;b3be&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Outside the function, a is non-const, so we can change it freely.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;b3f4&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 2: Array Parameter&lt;/h2&gt;
&lt;p id=&quot;10c4&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Arrays are passed as pointers, not copies, so const becomes more critical.&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

void printArray(const int arr[], int size) {
    // arr[0] = 100; // Error: assignment of read-only location
    for (int i = 0; i &amp;lt; size; i++) {
        cout &amp;lt;&amp;lt; arr[i] &amp;lt;&amp;lt; &quot; &quot;;
    }
    cout &amp;lt;&amp;lt; endl;
}

int main() {
    int numbers[] = {1, 2, 3, 4};
    int size = 4;

    printArray(numbers, size); // Array is read-only inside function
    numbers[0] = 10; // Modify outside function
    cout &amp;lt;&amp;lt; &quot;After modification: &quot;;
    printArray(numbers, size);

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;ac2b&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;1 2 3 4
After modification: 10 2 3 4&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;4423&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Key Point:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;bbb4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;const int arr[] prevents the function from modifying the array&amp;rsquo;s elements.&lt;/li&gt;
&lt;li id=&quot;6504&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Outside the function, numbers is non-const, so we can still change it. The const restriction only applies inside printArray.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;4641&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. const Inside vs. Outside Functions&lt;/h1&gt;
&lt;p id=&quot;0e8c&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The const keyword&amp;rsquo;s scope is local to where it&amp;rsquo;s applied. Data that&amp;rsquo;s const inside a function can still be modified outside if it&amp;rsquo;s not declared const there. Let&amp;rsquo;s explore this further.&lt;/p&gt;
&lt;h2 id=&quot;4397&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 3: Mixing const and Non-const&lt;/h2&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

void processData(const int value, const int arr[], int size) {
    cout &amp;lt;&amp;lt; &quot;Value = &quot; &amp;lt;&amp;lt; value &amp;lt;&amp;lt; &quot;, Array = &quot;;
    for (int i = 0; i &amp;lt; size; i++) {
        cout &amp;lt;&amp;lt; arr[i] &amp;lt;&amp;lt; &quot; &quot;;
    }
    cout &amp;lt;&amp;lt; endl;
}

int main() {
    int num = 5;
    int data[] = {10, 20, 30};

    processData(num, data, 3); // Pass non-const data to const parameters

    num = 15; // Modify num
    data[0] = 100; // Modify data
    cout &amp;lt;&amp;lt; &quot;After changes: &quot;;
    processData(num, data, 3);

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;f12b&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Value = 5, Array = 10 20 30
After changes: Value = 15, Array = 100 20 30&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;c524&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;402a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Inside processData, value and arr are const, so the function can&amp;rsquo;t change them.&lt;/li&gt;
&lt;li id=&quot;d81e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Outside, num and data are non-const, so we can modify them freely. The const in the function doesn&amp;rsquo;t &amp;ldquo;lock&amp;rdquo; the original data &amp;mdash; it just restricts what the function can do.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;babb&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. Challenges with const and Function Calls&lt;/h1&gt;
&lt;p id=&quot;7593&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;What happens if a function with const parameters needs to call another function? If the second function doesn&amp;rsquo;t expect const data, you&amp;rsquo;ll run into issues. Let&amp;rsquo;s see this in action.&lt;/p&gt;
&lt;h2 id=&quot;23ab&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Example 4: Calling a Non-const Function&lt;/h2&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

void modifyArray(int arr[], int size) { // Non-const parameter
    arr[0] = 999;
    cout &amp;lt;&amp;lt; &quot;Modified in modifyArray: &quot; &amp;lt;&amp;lt; arr[0] &amp;lt;&amp;lt; endl;
}

void processArray(const int arr[], int size) {
    cout &amp;lt;&amp;lt; &quot;In processArray: &quot; &amp;lt;&amp;lt; arr[0] &amp;lt;&amp;lt; endl;
    // modifyArray(arr, size); // Error: cannot convert 'const int*' to 'int*'
}

int main() {
    int numbers[] = {1, 2, 3};
    processArray(numbers, 3);
    modifyArray(numbers, 3); // Works fine here
    processArray(numbers, 3);

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;17f3&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;In processArray: 1
Modified in modifyArray: 999
In processArray: 999&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;a845&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Problem:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e896&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;processArray takes const int arr[], so arr is read-only. =&amp;gt; Because of this, you&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;cannot call&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;modifyArray(arr, size)&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;from within&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;processArray. The reason is that&lt;span&gt;&amp;nbsp;&lt;/span&gt;modifyArray&lt;span&gt;&amp;nbsp;&lt;/span&gt;expects a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;non-const&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;array (int arr[]), which it modifies. =&amp;gt; The compiler prevents this with an error like: Error: cannot convert &amp;lsquo;const int*&amp;rsquo; to &amp;lsquo;int*&amp;rsquo;&amp;rdquo;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;b904&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Conclusion&lt;/h1&gt;
&lt;p id=&quot;8e71&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The const modifier in C++ is all about control. It lets you:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;2c0a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Protect data inside functions from being modified (const int x, const int arr[]).&lt;/li&gt;
&lt;li id=&quot;4d2e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Keep flexibility outside functions where data isn&amp;rsquo;t const.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;9ee8&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Whether you&amp;rsquo;re working with scalars, arrays, or multi-dimensional structures, const helps you write safer, more intentional code. It&amp;rsquo;s especially valuable in large projects where tracking modifications can get messy.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>const arrays</category>
      <category>cpp programming</category>
      <category>Data Protection</category>
      <category>functional programming</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/56</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp021-Const-Modifier-in-C#entry56comment</comments>
      <pubDate>Sat, 5 Apr 2025 20:00:16 +0900</pubDate>
    </item>
    <item>
      <title>cpp_020: Multi-Dimensional Arrays vs. Nested std::vector in C++ &amp;mdash; Understanding the Basics with Examples</title>
      <link>https://codeaddict.tistory.com/entry/cpp020-Multi-Dimensional-Arrays-vs-Nested-stdvector-in-C-%E2%80%94-Understanding-the-Basics-with-Examples</link>
      <description>&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p id=&quot;beb2&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In this tutorial, we explore multi-dimensional collections in C++, including multi-dimensional arrays and nested&lt;span&gt;&amp;nbsp;&lt;/span&gt;std::vector&lt;span&gt;&amp;nbsp;&lt;/span&gt;structures, which are commonly used to represent data in multiple dimensions, such as matrices or grids.&lt;/p&gt;
&lt;p id=&quot;a6e7&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Throughout this tutorial, we will:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e98e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Introduce multi-dimensional C-style arrays and nested&lt;span&gt;&amp;nbsp;&lt;/span&gt;std::vector&lt;span&gt;&amp;nbsp;&lt;/span&gt;structures.&lt;/li&gt;
&lt;li id=&quot;662d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Demonstrate how to declare and use them with basic examples.&lt;/li&gt;
&lt;li id=&quot;5283&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Explain how to pass them to functions.&lt;/li&gt;
&lt;li id=&quot;4587&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Present a practical problem and solve it using both approaches.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;f5e8&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;1- Basics of Multi-Dimensional Arrays and Nested Vectors&lt;/h1&gt;
&lt;h2 id=&quot;3bad&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;1.1 Multi-Dimensional C-Style Arrays&lt;/h2&gt;
&lt;p id=&quot;4743&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;A multi-dimensional array is an array of arrays. For example, a 2D array can represent a matrix with rows and columns. Its size is fixed at compile time.&lt;/p&gt;
&lt;p id=&quot;6a8e&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Declaration:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;markdown&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;int arr[rows][cols]; // e.g., int arr[2][3] for 2 rows, 3 columns&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;9549&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;1.2 Nested std::vector (Vector of Vectors)&lt;/h2&gt;
&lt;p id=&quot;6291&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;A nested std::vector is a dynamic structure where each element of the outer vector is itself a vector. There are two common ways to declare it:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;f1e7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Pre-sized Declaration:&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vec(rows, vector&amp;lt;int&amp;gt;(cols)); // e.g., 2 rows, 3 columns&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;410f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Creates a vector with rows rows, each containing a vector of cols elements, initialized to 0.&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;f20a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Empty Declaration with Assignment:&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vec; // Starts empty
vec = {{1, 2, 3}, {4, 5, 6}}; // Assigns a 2x3 structure&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;b8a6&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Comparison with Examples:&lt;/b&gt;&lt;/p&gt;
&lt;p id=&quot;e927&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s see these in action to understand how they differ.&lt;/p&gt;
&lt;p id=&quot;525c&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;-Pre-sized Example:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    // Declare a 2x3 nested vector (not empty, initialized with 0s)
    vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vec(2, vector&amp;lt;int&amp;gt;(3));

    // Print initial contents
    cout &amp;lt;&amp;lt; &quot;Pre-sized 2x3 Nested Vector (initial):\n&quot;;
    for (int i = 0; i &amp;lt; vec.size(); i++) {
        for (int j = 0; j &amp;lt; vec[i].size(); j++) {
            cout &amp;lt;&amp;lt; vec[i][j] &amp;lt;&amp;lt; &quot; &quot;;
        }
        cout &amp;lt;&amp;lt; endl;
    }

    // Assign specific values
    vec[0] = {1, 2, 3}; // Replace row 0
    vec[1] = {4, 5, 6}; // Replace row 1

    // Print updated contents
    cout &amp;lt;&amp;lt; &quot;\nPre-sized 2x3 Nested Vector (updated):\n&quot;;
    for (int i = 0; i &amp;lt; vec.size(); i++) {
        for (int j = 0; j &amp;lt; vec[i].size(); j++) {
            cout &amp;lt;&amp;lt; vec[i][j] &amp;lt;&amp;lt; &quot; &quot;;
        }
        cout &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;cb80&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Pre-sized 2x3 Nested Vector (initial):
0 0 0
0 0 0

Pre-sized 2x3 Nested Vector (updated):
1 2 3
4 5 6&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;839e&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;-Empty with Assignment Example:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    // Declare an empty nested vector first
    vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vec;

    // Print initial size
    cout &amp;lt;&amp;lt; &quot;Initial size of empty vector: &quot; &amp;lt;&amp;lt; vec.size() &amp;lt;&amp;lt; endl;

    // Assign the 2x3 structure in one step
    vec = {{1, 2, 3}, {4, 5, 6}};

    // Print the result
    cout &amp;lt;&amp;lt; &quot;\nAssigned 2x3 Nested Vector:\n&quot;;
    for (int i = 0; i &amp;lt; vec.size(); i++) {
        for (int j = 0; j &amp;lt; vec[i].size(); j++) {
            cout &amp;lt;&amp;lt; vec[i][j] &amp;lt;&amp;lt; &quot; &quot;;
        }
        cout &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;4025&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Initial size of empty vector: 0

Assigned 2x3 Nested Vector:
1 2 3
4 5 6&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;f018&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation of Differences:&lt;/b&gt;&lt;/p&gt;
&lt;p id=&quot;a6a7&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;-Pre-sized (vec(rows, vector&amp;lt;int&amp;gt;(cols))):&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c5fe&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Immediately creates a 2x3 structure with all elements set to 0.&lt;/li&gt;
&lt;li id=&quot;6af3&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Size is fixed at declaration (vec.size() == 2, vec[0].size() == 3).&lt;/li&gt;
&lt;li id=&quot;2c02&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;You replace values afterward (e.g., vec[0] = {1, 2, 3}).&lt;/li&gt;
&lt;li id=&quot;6d41&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Best when you need a specific size upfront and plan to fill it later.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;2e97&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;-Empty with Assignment (vec; vec = {&amp;hellip;}):&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;a5ad&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Starts empty (vec.size() == 0), with no structure.&lt;/li&gt;
&lt;li id=&quot;7f63&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Assignment (vec = {{1, 2, 3}, {4, 5, 6}}) sets the size and values in one step.&lt;/li&gt;
&lt;li id=&quot;4530&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Simpler if you have all the data ready and want to initialize it directly.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;f75e&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;-Key Difference:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;The pre-sized method gives you a &amp;ldquo;blank slate&amp;rdquo; with a defined shape, while the empty method starts with nothing until you assign the full structure.&lt;/p&gt;
&lt;h1 id=&quot;94e1&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2- Key Examples with Explanations&lt;/h1&gt;
&lt;h2 id=&quot;7304&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;2.1 Basic Usage with Loops&lt;/h2&gt;
&lt;p id=&quot;2efd&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s compare a 2D array and both nested vector declarations, initializing them with {1, 2, 3}, {4, 5, 6} and printing with loops.&lt;/p&gt;
&lt;p id=&quot;d1f0&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Code:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    // 2D C-style array: 2 rows, 3 columns
    int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};

    // Nested vector (pre-sized): 2 rows, 3 columns
    vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vec1(2, vector&amp;lt;int&amp;gt;(3));
    vec1[0] = {1, 2, 3};
    vec1[1] = {4, 5, 6};

    // Nested vector (empty then assigned): 2 rows, 3 columns
    vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vec2;
    vec2 = {{1, 2, 3}, {4, 5, 6}};

    // Printing 2D array
    cout &amp;lt;&amp;lt; &quot;2D Array:\n&quot;;
    for (int i = 0; i &amp;lt; 2; i++) {
        for (int j = 0; j &amp;lt; 3; j++) {
            cout &amp;lt;&amp;lt; arr[i][j] &amp;lt;&amp;lt; &quot; &quot;;
        }
        cout &amp;lt;&amp;lt; endl;
    }

    // Printing pre-sized nested vector
    cout &amp;lt;&amp;lt; &quot;\nPre-sized Nested Vector:\n&quot;;
    for (int i = 0; i &amp;lt; vec1.size(); i++) {
        for (int j = 0; j &amp;lt; vec1[i].size(); j++) {
            cout &amp;lt;&amp;lt; vec1[i][j] &amp;lt;&amp;lt; &quot; &quot;;
        }
        cout &amp;lt;&amp;lt; endl;
    }

    // Printing assigned nested vector
    cout &amp;lt;&amp;lt; &quot;\nAssigned Nested Vector:\n&quot;;
    for (int i = 0; i &amp;lt; vec2.size(); i++) {
        for (int j = 0; j &amp;lt; vec2[i].size(); j++) {
            cout &amp;lt;&amp;lt; vec2[i][j] &amp;lt;&amp;lt; &quot; &quot;;
        }
        cout &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;fe4d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;2D Array:
1 2 3
4 5 6

Pre-sized Nested Vector:
1 2 3
4 5 6

Assigned Nested Vector:
1 2 3
4 5 6&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;655a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;6459&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;2D Array:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Fixed at 2x3, initialized directly. Loops use hardcoded bounds.&lt;/li&gt;
&lt;li id=&quot;66b7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Pre-sized Vector (vec1):&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Starts as a 2x3 grid of 0s, then updated with values. Size is set at declaration.&lt;/li&gt;
&lt;li id=&quot;03d0&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Assigned Vector (vec2):&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Starts empty, then assigned the full structure. Size is set by the assignment.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;f144&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;2.2 Passing to Functions&lt;/h2&gt;
&lt;p id=&quot;0ad6&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s pass a 2D array and a nested vector (assigned method) to functions to sum their elements.&lt;/p&gt;
&lt;p id=&quot;4656&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Code:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

// Function for 2D array
int sumArray(int arr[][3], int rows) {
    int sum = 0;
    for (int i = 0; i &amp;lt; rows; i++) {
        for (int j = 0; j &amp;lt; 3; j++) {
            sum += arr[i][j];
        }
    }
    return sum;
}

// Function for nested vector
int sumVector(const vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt;&amp;amp; vec) {
    int sum = 0;
    for (int i = 0; i &amp;lt; vec.size(); i++) {
        for (int j = 0; j &amp;lt; vec[i].size(); j++) {
            sum += vec[i][j];
        }
    }
    return sum;
}

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

    // Nested vector (assigned method)
    vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vec;
    vec = {{1, 2, 3}, {4, 5, 6}};

    // Call functions
    cout &amp;lt;&amp;lt; &quot;Sum of 2D array: &quot; &amp;lt;&amp;lt; sumArray(arr, 2) &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Sum of nested vector: &quot; &amp;lt;&amp;lt; sumVector(vec) &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;dbbe&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Sum of 2D array: 21
Sum of nested vector: 21&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;092e&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;h2 id=&quot;a20a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;2D Array: Requires column size in the parameter (int arr[][3]).&lt;/h2&gt;
&lt;p id=&quot;533c&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;When passing a 2D C-style array to a function, the syntax int arr[][3] is used. Here&amp;rsquo;s what this means and why it&amp;rsquo;s required:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e5fd&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Column Size (Fixed):&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;The 3 in int arr[][3] specifies the number of columns, and it&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;must be provided&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;at compile time. This is because a 2D array in C++ is stored in memory as a contiguous block, and the compiler needs to know the column size to calculate the memory offset for each element. For example, to access arr[i][j], the compiler computes the address as base_address + (i * columns + j) * sizeof(int). Without the column size (3), it can&amp;rsquo;t determine where each row ends and the next begins.&lt;/li&gt;
&lt;li id=&quot;b43b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Row Size (Flexible):&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;The number of rows (the first dimension) is&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;not fixed&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;in the function parameter and can be passed as a separate argument (e.g., int rows). The empty brackets [] indicate that the function can accept a 2D array with any number of rows, as long as each row has exactly 3 columns. This makes the function reusable for arrays like int arr1[2][3] or int arr2[5][3], but the column size remains constant.&lt;/li&gt;
&lt;li id=&quot;74b8&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Why Fixed Columns?&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Unlike std::vector, a C-style array&amp;rsquo;s size is determined at compile time and can&amp;rsquo;t change at runtime. The column size being fixed in the parameter reflects this static nature. If you tried to use int arr[][] (no sizes specified), the compiler would throw an error because it lacks the information needed to navigate the array&amp;rsquo;s memory layout.&lt;/li&gt;
&lt;li id=&quot;ab99&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Example Context:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;In the function sumArray(int arr[][3], int rows), the 3 ensures the function knows each row has 3 elements, while rows (passed as 2 in the example) tells it how many rows to process. This combination allows the function to work with the fixed 2x3 array {{1, 2, 3}, {4, 5, 6}}.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;5303&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Nested Vector: Passed by reference, works with either method after initialization.&lt;/h2&gt;
&lt;p id=&quot;4c82&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;When passing a nested std::vector (e.g., vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt;) to a function, it&amp;rsquo;s typically passed by const reference (e.g., const vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt;&amp;amp; vec). Here&amp;rsquo;s a deeper look at how this works and what vec[i].size() means:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;b3de&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Passed by Reference:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;The &amp;amp; in const vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt;&amp;amp; vec means the vector is passed by reference, not copied. This is crucial because a nested vector can be large, and copying it would be slow and memory-intensive. The const ensures the function won&amp;rsquo;t modify the vector, making it safe for read-only operations like summing elements.&lt;/li&gt;
&lt;li id=&quot;1873&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Dynamic Sizes:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Unlike a 2D array, a nested vector&amp;rsquo;s sizes (both rows and columns) are&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;dynamic&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;and determined at runtime. The outer vector&amp;rsquo;s size (vec.size()) is the number of rows, and each inner vector&amp;rsquo;s size (vec[i].size()) is the number of columns in row i. These sizes aren&amp;rsquo;t fixed at compile time &amp;mdash; they&amp;rsquo;re stored as part of the vector&amp;rsquo;s internal data and can vary.&lt;/li&gt;
&lt;li id=&quot;2ac3&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;What is vec[i].size()?&lt;/b&gt;&lt;/li&gt;
&lt;li id=&quot;893c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;vec is the outer vector, and vec[i] accesses the i-th inner vector (a row).&lt;/li&gt;
&lt;li id=&quot;7d8b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;vec[i].size() returns the number of elements (columns) in that specific row. For example, in vec = {{1, 2, 3}, {4, 5, 6}}, vec[0].size() is 3 because the first row has 3 elements (1, 2, 3).&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;940d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;3- Problem and Solution&lt;/h1&gt;
&lt;p id=&quot;f1c2&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Problem:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Transpose a 2x3 matrix into a 3x2 matrix using a 2D array and a nested vector (pre-sized method).&lt;/p&gt;
&lt;p id=&quot;f4f1&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    // 2D array: 2x3
    int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int arrT[3][2];

    // Nested vector (pre-sized): 2x3
    vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vec(2, vector&amp;lt;int&amp;gt;(3));
    vec[0] = {1, 2, 3};
    vec[1] = {4, 5, 6};
    vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; vecT(3, vector&amp;lt;int&amp;gt;(2));

    // Transpose 2D array
    for (int i = 0; i &amp;lt; 2; i++) {
        for (int j = 0; j &amp;lt; 3; j++) {
            arrT[j][i] = arr[i][j];
        }
    }

    // Transpose nested vector
    for (int i = 0; i &amp;lt; vec.size(); i++) {
        for (int j = 0; j &amp;lt; vec[i].size(); j++) {
            vecT[j][i] = vec[i][j];
        }
    }

    // Print results
    cout &amp;lt;&amp;lt; &quot;Transposed 2D Array (3x2):\n&quot;;
    for (int i = 0; i &amp;lt; 3; i++) {
        for (int j = 0; j &amp;lt; 2; j++) {
            cout &amp;lt;&amp;lt; arrT[i][j] &amp;lt;&amp;lt; &quot; &quot;;
        }
        cout &amp;lt;&amp;lt; endl;
    }

    cout &amp;lt;&amp;lt; &quot;\nTransposed Nested Vector (3x2):\n&quot;;
    for (int i = 0; i &amp;lt; vecT.size(); i++) {
        for (int j = 0; j &amp;lt; vecT[i].size(); j++) {
            cout &amp;lt;&amp;lt; vecT[i][j] &amp;lt;&amp;lt; &quot; &quot;;
        }
        cout &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;ad39&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Transposed 2D Array (3x2):
1 4 
2 5 
3 6 

Transposed Nested Vector (3x2):
1 4 
2 5 
3 6 &lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;4a62&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;708b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;2D Array:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Fixed sizes, transposed by swapping indices.&lt;/li&gt;
&lt;li id=&quot;4c99&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Nested Vector:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Pre-sized method used for consistency, transposed similarly.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>2D array</category>
      <category>cpp programming</category>
      <category>multi dimensional arrays</category>
      <category>nested vector</category>
      <category>vector of vectors</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/55</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp020-Multi-Dimensional-Arrays-vs-Nested-stdvector-in-C-%E2%80%94-Understanding-the-Basics-with-Examples#entry55comment</comments>
      <pubDate>Sat, 5 Apr 2025 19:59:04 +0900</pubDate>
    </item>
    <item>
      <title>cpp_019: Writing to Files with ofstream in C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp019-Writing-to-Files-with-ofstream-in-C</link>
      <description>&lt;p id=&quot;2ee0&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;When you need to save data from your C++ program to a file,&lt;span&gt;&amp;nbsp;&lt;/span&gt;ofstream&lt;span&gt;&amp;nbsp;&lt;/span&gt;(output file stream) is what you'll use. It's part of the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;lt;fstream&amp;gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;library and works similarly to writing to the console with&lt;span&gt;&amp;nbsp;&lt;/span&gt;cout, but instead sends data to a file.&lt;/p&gt;
&lt;h1 id=&quot;9774&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Basic Syntax&lt;/h1&gt;
&lt;p id=&quot;e386&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;First, you need to include the right header:&lt;/p&gt;
&lt;pre class=&quot;autoit&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;fstream&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;cabd&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Creating and using an&lt;span&gt;&amp;nbsp;&lt;/span&gt;ofstream&lt;span&gt;&amp;nbsp;&lt;/span&gt;has three main steps:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;41bf&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Create an&lt;span&gt;&amp;nbsp;&lt;/span&gt;ofstream&lt;span&gt;&amp;nbsp;&lt;/span&gt;object and open a file&lt;/li&gt;
&lt;li id=&quot;3d4c&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Check if the file opened successfully&lt;/li&gt;
&lt;li id=&quot;2830&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Write data to the file&lt;/li&gt;
&lt;li id=&quot;1ee1&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Close the file (automatically happens when the object is destroyed, but good to do explicitly)&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;stata&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;fstream&amp;gt; // Include this to use ofstream

std::ofstream file;              // Create an ofstream object
file.open(&quot;filename.txt&quot;);       // Open a file (creates it if it doesn&amp;rsquo;t exist)
file &amp;lt;&amp;lt; &quot;Stuff to write&quot;;        // Write to the file
file.close();&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;629d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;#include &amp;lt;fstream&amp;gt;&lt;/b&gt;: Brings in the file-handling tools.&lt;/li&gt;
&lt;li id=&quot;0829&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::ofstream file;&lt;/b&gt;: Makes an object called file (name it whatever you want).&lt;/li&gt;
&lt;li id=&quot;7c48&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;file.open(&amp;ldquo;filename.txt&amp;rdquo;)&lt;/b&gt;: Opens (or creates) the file in the same folder as your program.&lt;/li&gt;
&lt;li id=&quot;3ec1&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;file &amp;lt;&amp;lt; &amp;ldquo;text&amp;rdquo;&lt;/b&gt;: Uses the &amp;lt;&amp;lt; operator (like cout) to write.&lt;/li&gt;
&lt;li id=&quot;1841&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;file.close()&lt;/b&gt;: Shuts the file to save changes and free resources.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;ec5e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;You can also combine opening and creating in one line:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;std::ofstream file(&quot;filename.txt&quot;);&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;e85f&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example 1: Writing a Simple Message&lt;/h1&gt;
&lt;p id=&quot;c2a4&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s start basic &amp;mdash; writing a line to a file.&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;fstream&amp;gt;
#include &amp;lt;string&amp;gt;

int main() {
    std::ofstream file(&quot;message.txt&quot;);
    file &amp;lt;&amp;lt; &quot;Hello from C++!\n&quot;; // \n adds a newline
    file.close();
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;3200&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;What Happens:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e48c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Creates (or overwrites) message.txt in your program&amp;rsquo;s folder.&lt;/li&gt;
&lt;li id=&quot;c2cf&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Writes &amp;ldquo;Hello from C++!&amp;rdquo; to it.&lt;/li&gt;
&lt;li id=&quot;3673&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Closes the file.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;50d2&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Key Parts:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;5aa7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;std::ofstream file(&amp;ldquo;message.txt&amp;rdquo;): Opens the file right away.&lt;/li&gt;
&lt;li id=&quot;ada2&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;file &amp;lt;&amp;lt;: Sends the text to the file, just like cout.&lt;/li&gt;
&lt;li id=&quot;b99e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;file.close(): Saves and finishes up.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;c49c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Check message.txt after running &amp;mdash; it&amp;rsquo;ll have your message!&lt;/p&gt;
&lt;h1 id=&quot;9ab0&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example 2: Saving User Input&lt;/h1&gt;
&lt;p id=&quot;00aa&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Now, let&amp;rsquo;s save something the user types.&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;fstream&amp;gt;
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;

int main() {
    std::ofstream file(&quot;note.txt&quot;);
    std::string userInput;
    
    std::cout &amp;lt;&amp;lt; &quot;Type a note: &quot;;
    std::getline(std::cin, userInput); // Get a full line
    
    file &amp;lt;&amp;lt; &quot;Note: &quot; &amp;lt;&amp;lt; userInput &amp;lt;&amp;lt; &quot;\n&quot;;
    file.close();
    
    std::cout &amp;lt;&amp;lt; &quot;Saved to note.txt!\n&quot;;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;e047&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;What Happens:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;465a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Asks for input (e.g., &amp;ldquo;Buy milk&amp;rdquo;).&lt;/li&gt;
&lt;li id=&quot;44b0&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Writes &amp;ldquo;Note: Buy milk&amp;rdquo; to note.txt.&lt;/li&gt;
&lt;li id=&quot;a962&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Tells you it&amp;rsquo;s saved.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;02cf&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Key Parts:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;cf1f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;std::getline(std::cin, userInput): Grabs a whole line (spaces included), unlike cin &amp;gt;&amp;gt;.&lt;/li&gt;
&lt;li id=&quot;3aaf&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;file &amp;lt;&amp;lt; &amp;ldquo;Note: &amp;ldquo; &amp;lt;&amp;lt; userInput: Chains text and the variable together.&lt;/li&gt;
&lt;li id=&quot;dd13&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;File gets created/overwritten in your program&amp;rsquo;s directory.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;317e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Run it, type something, and check note.txt.&lt;/p&gt;</description>
      <category>C++ Beginner</category>
      <category>cpp beginner</category>
      <category>cpp programming</category>
      <category>File Handling</category>
      <category>ofstream</category>
      <category>writing ro files</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/54</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp019-Writing-to-Files-with-ofstream-in-C#entry54comment</comments>
      <pubDate>Sat, 5 Apr 2025 19:57:48 +0900</pubDate>
    </item>
    <item>
      <title>cpp_019: Basics of Functions, Methods, Static Methods, and Constructors in C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp019-Basics-of-Functions-Methods-Static-Methods-and-Constructors-in-C</link>
      <description>&lt;p id=&quot;80e4&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;This is a beginner-friendly lesson on four key programming ideas:&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;functions&lt;/b&gt;,&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;methods&lt;/b&gt;,&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;static methods&lt;/b&gt;, and&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;constructors&lt;/b&gt;. I&amp;rsquo;ll use the circle and square analogy to make it visual and simple, explain what an&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;object&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;is first, and compare to Python at the end for those familiar with it. No deep OOP yet &amp;mdash; just the basics!&lt;/p&gt;
&lt;h1 id=&quot;55f8&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. Object (First, for Context)&lt;/h1&gt;
&lt;h1 id=&quot;97ea&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;What is an Object?&lt;/h1&gt;
&lt;p id=&quot;a881&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;An&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;object&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a specific&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;thing&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;in your program &amp;mdash; like a real dog, car, or person. It&amp;rsquo;s made from a blueprint called a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;class&lt;/b&gt;. In our analogy:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;25a8&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Square&lt;/b&gt;: The object (a specific thing, like &amp;ldquo;Buddy the dog&amp;rdquo;).&lt;/li&gt;
&lt;li id=&quot;b926&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Class&lt;/b&gt;: The design for all squares (e.g., &amp;ldquo;Dog blueprint&amp;rdquo;).&lt;/li&gt;
&lt;li id=&quot;b1aa&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Example&lt;/b&gt;: If &amp;ldquo;Dog&amp;rdquo; is the class (blueprint), &amp;ldquo;Buddy&amp;rdquo; is an object (a square made from it).&lt;/li&gt;
&lt;li id=&quot;096c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Why&lt;/b&gt;: Objects let us work with real instances, not just ideas.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;a253&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Function&lt;/h1&gt;
&lt;h1 id=&quot;42f2&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;What is a Function?&lt;/h1&gt;
&lt;p id=&quot;7ac4&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;A&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;function&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a standalone&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;action&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;mdash; a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;circle&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;floating by itself. It&amp;rsquo;s not tied to any square (thing). You call it directly to do a task.&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;0999&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Picture&lt;/b&gt;: A single circle, like a button labeled &amp;ldquo;Say Hello.&amp;rdquo;&lt;/li&gt;
&lt;li id=&quot;94d2&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Purpose&lt;/b&gt;: Does a job anytime you need it, like printing or calculating.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;1e1d&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example&lt;/h1&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;

// Function (a lone circle)
void sayHello() {
    std::cout &amp;lt;&amp;lt; &quot;Hello!&quot; &amp;lt;&amp;lt; std::endl;
}

int main() {
    sayHello(); // Press the circle button =&amp;gt; Output: Hello!
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;4531&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Method&lt;/h1&gt;
&lt;h1 id=&quot;626b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;What is a Method?&lt;/h1&gt;
&lt;p id=&quot;35cc&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;A&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;method&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;is an&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;action&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(circle) that belongs&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;inside a specific square&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(object). It&amp;rsquo;s something the object can do, and you call it with a dot: square.circle().&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;ecf5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Picture&lt;/b&gt;: A square (the object) with a circle inside labeled &amp;ldquo;Bark.&amp;rdquo;&lt;/li&gt;
&lt;li id=&quot;f353&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Purpose&lt;/b&gt;: Lets a specific thing perform its own actions.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;a020&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example&lt;/h1&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;

class Dog { // Blueprint for squares
public:
    std::string name;

    // Method (circle inside the square)
    void bark() {
        std::cout &amp;lt;&amp;lt; name &amp;lt;&amp;lt; &quot; says Woof!&quot; &amp;lt;&amp;lt; std::endl;
    }
};

int main() {
    Dog myDog;        // A square (object)
    myDog.name = &quot;Buddy&quot;;
    myDog.bark();     // Press the circle inside myDog =&amp;gt; Output: Buddy says Woof!
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;380b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;415b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;myDog is the square (object).&lt;/li&gt;
&lt;li id=&quot;a015&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;bark() is the circle inside it. You call it with myDog.bark() because it&amp;rsquo;s tied to that square.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;0152&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Another Example (std::string)&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;

int main() {
    std::string name = &quot;Jane&quot;; // A square (string object)
    int len = name.length();   // Circle inside the square =&amp;gt; Output: 4
    std::cout &amp;lt;&amp;lt; &quot;Length: &quot; &amp;lt;&amp;lt; len &amp;lt;&amp;lt; std::endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;530f&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation&lt;/b&gt;: name is a square, and length() is its circle. You call name.length().&lt;/p&gt;
&lt;h1 id=&quot;2a3b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. Static Method&lt;/h1&gt;
&lt;h1 id=&quot;019c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;What is a Static Method?&lt;/h1&gt;
&lt;p id=&quot;f541&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;A&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;static method&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;is an&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;action&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(circle) attached to the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;class blueprint&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(the square&amp;rsquo;s design), not a specific square (object). It works for the whole group, not one instance.&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;3008&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Picture&lt;/b&gt;: A big square labeled &amp;ldquo;User Blueprint&amp;rdquo; with a circle stuck to its edge labeled &amp;ldquo;Show Count.&amp;rdquo;&lt;/li&gt;
&lt;li id=&quot;87b9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Purpose&lt;/b&gt;: Does something related to all objects of that type, not one specific object.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;8313&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example&lt;/h1&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;

class User { // Blueprint for squares
public:
    static int count; // Shared by all squares

    // Static method (circle on the blueprint)
    static void showCount() {
        std::cout &amp;lt;&amp;lt; &quot;Total users: &quot; &amp;lt;&amp;lt; count &amp;lt;&amp;lt; std::endl;
    }
};

int User::count = 0; // Set up the shared number

int main() {
    User::count = 2;    // Set total users
    User::showCount();  // Press the circle on the blueprint =&amp;gt; Output: Total users: 2
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;6bd5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Explanation&lt;/b&gt;:&lt;/li&gt;
&lt;li id=&quot;554c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;User is the blueprint (big square).&lt;/li&gt;
&lt;li id=&quot;69ff&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;showCount() is a circle on the blueprint&amp;rsquo;s edge. Call it with User::showCount() &amp;mdash; no specific square needed.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;5a77&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Method vs. Static Method&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c0e4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Method&lt;/b&gt;: Inside a square (e.g., user1.speak() &amp;mdash; one user speaks).&lt;/li&gt;
&lt;li id=&quot;8995&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Static Method&lt;/b&gt;: On the blueprint (e.g., User::showCount() &amp;mdash; counts all users).&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;cbc1&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;5. Constructor&lt;/h1&gt;
&lt;h1 id=&quot;bfdb&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;What is a Constructor?&lt;/h1&gt;
&lt;p id=&quot;914b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;A&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;constructor&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a special&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;action&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(circle) that&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;builds a new square&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(object) when you create it. It runs automatically to set up the object&amp;rsquo;s starting stuff.&lt;/p&gt;
&lt;h1 id=&quot;a8b6&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example&lt;/h1&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;

class User { // Blueprint for squares
public:
    std::string name;

    // Constructor (circle that builds the square)
    User(std::string userName) {
        name = userName;
    }

    void speak() { // Method (circle inside the square)
        std::cout &amp;lt;&amp;lt; &quot;Hi, I&amp;rsquo;m &quot; &amp;lt;&amp;lt; name &amp;lt;&amp;lt; std::endl;
    }
};

int main() {
    User user1(&quot;Jane&quot;); // Magic circle builds square user1
    User user2(&quot;Sara&quot;); // Magic circle builds square user2
    user1.speak();      // Output: Hi, I&amp;rsquo;m Jane
    user2.speak();      // Output: Hi, I&amp;rsquo;m Sara
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;8f1d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Explanation&lt;/b&gt;:&lt;/li&gt;
&lt;li id=&quot;5939&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;User(std::string userName) is the constructor circle. It builds user1 and user2 squares with names.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;0ae5&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Constructor vs. Function&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;a4f0&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Function&lt;/b&gt;: A free circle you call anytime (e.g., sayHello()).&lt;/li&gt;
&lt;li id=&quot;7bb4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Constructor&lt;/b&gt;: A circle that builds a square once, when you make it (e.g., User(&amp;ldquo;Jane&amp;rdquo;)).&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;ecfb&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Class vs. Object (Quick Note)&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;a52f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Class&lt;/b&gt;: The blueprint (big square design) &amp;mdash; e.g., User.&lt;/li&gt;
&lt;li id=&quot;225f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Object&lt;/b&gt;: A specific square made from it &amp;mdash; e.g., user1, user2.&lt;/li&gt;
&lt;li id=&quot;7363&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;More Later&lt;/b&gt;: In OOP, we&amp;rsquo;ll dive deeper into this!&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;7d5b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Future Topic: Destructor&lt;/h1&gt;
&lt;p id=&quot;0bdc&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;A&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;destructor&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a circle that cleans up a square when it&amp;rsquo;s done. Preview:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;

class User {
public:
    std::string name;

    User(std::string userName) { // Constructor
        name = userName;
        std::cout &amp;lt;&amp;lt; name &amp;lt;&amp;lt; &quot; created!&quot; &amp;lt;&amp;lt; std::endl;
    }

    ~User() { // Destructor
        std::cout &amp;lt;&amp;lt; name &amp;lt;&amp;lt; &quot; destroyed!&quot; &amp;lt;&amp;lt; std::endl;
    }
};

int main() {
    User user1(&quot;Jane&quot;); // Output: Jane created!
    return 0;           // Output: Jane destroyed!
}&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;250e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Explanation: Automatic Destructor Call&lt;/h1&gt;
&lt;p id=&quot;d2ce&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In C++, the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;destructor&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(~User()) is a special method that gets called&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;automatically&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;when an object&amp;rsquo;s&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;lifetime ends&lt;/b&gt;. You don&amp;rsquo;t need to call it yourself with something like ~user1() &amp;mdash; C++ handles it for you. Let&amp;rsquo;s break it down:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;5461&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Creating the Object&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c694&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;User user1(&amp;ldquo;Jane&amp;rdquo;); creates an object called user1.&lt;/li&gt;
&lt;li id=&quot;9942&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;This line triggers the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;constructor&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(User(std::string userName)), which sets name = &amp;ldquo;Jane&amp;rdquo; and prints &amp;ldquo;Jane created!&amp;rdquo;.&lt;/li&gt;
&lt;li id=&quot;14be&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;user1 is now a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;square&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(using our analogy) with &amp;ldquo;Jane&amp;rdquo; inside it, built by the constructor circle.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;f235&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Object&amp;rsquo;s Lifetime&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;8dbb&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;user1 is created inside the main() function. In C++, objects like this have a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;scope&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;&amp;mdash; they only live as long as the block of code they&amp;rsquo;re in (here, the {} of main()).&lt;/li&gt;
&lt;li id=&quot;1e8f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;While main() is running, user1 exists and is usable.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;d34b&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. End of Scope&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;4f9f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;When return 0; happens, main() finishes, and the program ends.&lt;/li&gt;
&lt;li id=&quot;69bf&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;At this point, the scope of main() closes (the } at the end), and any objects created inside it &amp;mdash; like user1 &amp;mdash; reach the end of their lifetime.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;14a5&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. Destructor Runs Automatically&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;86fd&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;C++ automatically calls the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;destructor&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(~User()) for user1 when it goes out of scope (i.e., when main() ends).&lt;/li&gt;
&lt;li id=&quot;e63f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The destructor prints &amp;ldquo;Jane destroyed!&amp;rdquo; and cleans up user1 (in this case, just the std::string name is destroyed automatically by its own destructor).&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;5be4&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Key Point&lt;/b&gt;: You didn&amp;rsquo;t write ~user1() because you&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;can&amp;rsquo;t&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;don&amp;rsquo;t need to&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;call the destructor manually for objects like this. C++ does it for you when the object&amp;rsquo;s life is over.&lt;/p&gt;
&lt;p id=&quot;df96&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&amp;mdash; If you don&amp;rsquo;t define a destructor, C++ silently provides a default one that automatically cleans up basic member variables (like std::string) when the object&amp;rsquo;s scope ends.&lt;/p&gt;
&lt;p id=&quot;6183&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&amp;mdash; When you define a destructor like ~User() { std::cout &amp;lt;&amp;lt; name &amp;lt;&amp;lt; &amp;ldquo; destroyed!&amp;rdquo; &amp;lt;&amp;lt; std::endl; }, it&amp;rsquo;s just for adding custom actions &amp;mdash; like printing a message &amp;mdash; since the default cleanup still happens for name; it doesn&amp;rsquo;t change the memory management here, it only lets you see when the object is destroyed.&lt;/p&gt;
&lt;h1 id=&quot;1d3a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot;&gt;Summary with Analogy&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;dfda&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Function&lt;/b&gt;: Lone circle (action) &amp;mdash; sayHello().&lt;/li&gt;
&lt;li id=&quot;9023&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Method&lt;/b&gt;: Circle inside a square (object&amp;rsquo;s action) &amp;mdash; myDog.bark().&lt;/li&gt;
&lt;li id=&quot;0370&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Static Method&lt;/b&gt;: Circle on the blueprint (class action) &amp;mdash; User::showCount().&lt;/li&gt;
&lt;li id=&quot;7390&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Constructor&lt;/b&gt;: Magic circle building a square &amp;mdash; User(&amp;ldquo;Jane&amp;rdquo;).&lt;/li&gt;
&lt;/ul&gt;</description>
      <category>C++ Beginner</category>
      <category>cpp constructor</category>
      <category>cpp functionsstatic</category>
      <category>cpp methods</category>
      <category>destructor</category>
      <category>Methods</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/53</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp019-Basics-of-Functions-Methods-Static-Methods-and-Constructors-in-C#entry53comment</comments>
      <pubDate>Sat, 5 Apr 2025 19:56:41 +0900</pubDate>
    </item>
    <item>
      <title>cpp_018: Switch and Enum in C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp018-Switch-and-Enum-in-C</link>
      <description>&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p id=&quot;ff38&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Switch statements and enums are powerful tools in C++ that help you write clean, efficient, and readable decision-making logic. In this tutorial, we&amp;rsquo;ll explore their syntax, functionality, and practical examples, followed by problems and solutions to reinforce your understanding.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;1aa6&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. Switch Statement&lt;/h1&gt;
&lt;p id=&quot;b04d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The&lt;span&gt;&amp;nbsp;&lt;/span&gt;switch&lt;span&gt;&amp;nbsp;&lt;/span&gt;statement allows you to test a variable or expression against multiple cases and execute the corresponding block of code.&lt;/p&gt;
&lt;h2 id=&quot;ccaf&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Syntax:&lt;/h2&gt;
&lt;pre class=&quot;groovy&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;switch (expression) {
    case constant1:
        // Code block 1
        break;
    case constant2:
        // Code block 2
        break;
    default:
        // Default code block
}&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c0f2&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;expression&lt;/b&gt;: The variable or value being tested.&lt;/li&gt;
&lt;li id=&quot;5a40&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;case constant&lt;/b&gt;: Matches specific values of the expression.&lt;/li&gt;
&lt;li id=&quot;ee53&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;break&lt;/b&gt;: Terminates the switch case to prevent &quot;fall-through&quot; execution.&lt;/li&gt;
&lt;li id=&quot;1ece&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;default&lt;/b&gt;: Executes if none of the cases match.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;6767&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Enum (Enumeration)&lt;/h1&gt;
&lt;p id=&quot;3e43&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;An&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a user-defined data type that assigns names to integral constants, making your code more readable and maintainable.&lt;/p&gt;
&lt;h2 id=&quot;65c1&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Syntax:&lt;/h2&gt;
&lt;pre class=&quot;crystal&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;enum EnumName {
    constant1,
    constant2,
    constant3,
    // ...
};&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;405e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Enumerators are automatically assigned integer values starting from&lt;span&gt;&amp;nbsp;&lt;/span&gt;0&lt;span&gt;&amp;nbsp;&lt;/span&gt;unless explicitly specified.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;b2b7&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Example 1: Simple Switch with Enum&lt;/h1&gt;
&lt;p id=&quot;15ea&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s create a simple program that uses a&lt;span&gt;&amp;nbsp;&lt;/span&gt;switch&lt;span&gt;&amp;nbsp;&lt;/span&gt;statement with an&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;to represent days of the week.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };

int main() {
    Day today = Friday;

    switch (today) {
        case Monday:
            cout &amp;lt;&amp;lt; &quot;It's Monday. Back to work!&quot; &amp;lt;&amp;lt; endl;
            break;
        case Friday:
            cout &amp;lt;&amp;lt; &quot;It's Friday. The weekend is near!&quot; &amp;lt;&amp;lt; endl;
            break;
        case Sunday:
            cout &amp;lt;&amp;lt; &quot;It's Sunday. Relax and recharge!&quot; &amp;lt;&amp;lt; endl;
            break;
        default:
            cout &amp;lt;&amp;lt; &quot;It's a regular weekday.&quot; &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;1556&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Output:&lt;/h2&gt;
&lt;pre class=&quot;ada&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;It's Friday. The weekend is near!&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;10eb&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Explanation:&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e66a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;We define an&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;called&lt;span&gt;&amp;nbsp;&lt;/span&gt;Day&lt;span&gt;&amp;nbsp;&lt;/span&gt;to represent the days of the week.&lt;/li&gt;
&lt;li id=&quot;e71d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The&lt;span&gt;&amp;nbsp;&lt;/span&gt;switch&lt;span&gt;&amp;nbsp;&lt;/span&gt;statement checks the value of&lt;span&gt;&amp;nbsp;&lt;/span&gt;today&lt;span&gt;&amp;nbsp;&lt;/span&gt;and executes the corresponding case block.&lt;/li&gt;
&lt;li id=&quot;07ba&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Since&lt;span&gt;&amp;nbsp;&lt;/span&gt;today&lt;span&gt;&amp;nbsp;&lt;/span&gt;is set to&lt;span&gt;&amp;nbsp;&lt;/span&gt;Friday, the program prints the message for Friday.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;4f3f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. Example 2: Scenario with Explicit Enum Values&lt;/h1&gt;
&lt;p id=&quot;d943&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In this example, we&amp;rsquo;ll use an&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;with explicitly assigned values and a&lt;span&gt;&amp;nbsp;&lt;/span&gt;switch&lt;span&gt;&amp;nbsp;&lt;/span&gt;statement to suggest activities based on the weather.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

// Define an enum called Weather with explicit integer values for each weather type
enum Weather { Sunny = 1, Cloudy = 2, Rainy = 3, Snowy = 4 };

void suggestActivity(Weather w) {
    switch (w) {
        case Sunny:
            cout &amp;lt;&amp;lt; &quot;It's sunny! Go for a walk or a picnic.&quot; &amp;lt;&amp;lt; endl;
            break;
        case Cloudy:
            cout &amp;lt;&amp;lt; &quot;It's cloudy. A perfect day for indoor activities.&quot; &amp;lt;&amp;lt; endl;
            break;
        case Rainy:
            cout &amp;lt;&amp;lt; &quot;It's rainy. Stay indoors and read a book.&quot; &amp;lt;&amp;lt; endl;
            break;
        case Snowy:
            cout &amp;lt;&amp;lt; &quot;It's snowy. Time for some skiing or snowball fights!&quot; &amp;lt;&amp;lt; endl;
            break;
        default:
            cout &amp;lt;&amp;lt; &quot;Invalid weather type!&quot; &amp;lt;&amp;lt; endl;
    }
}

int main() {
    // Declare a variable of type Weather to store the current weather
    Weather currentWeather;

    // Declare an integer variable to store the user's input
    int input;

    // Ask the user to enter a number representing the weather type
    cout &amp;lt;&amp;lt; &quot;Enter the weather type (1: Sunny, 2: Cloudy, 3: Rainy, 4: Snowy): &quot;;
    cin &amp;gt;&amp;gt; input;  // Store the user's input in the variable 'input'

    // Convert the integer input to the Weather enum type using static_cast
    currentWeather = static_cast&amp;lt;Weather&amp;gt;(input);

    // Call the suggestActivity function and pass the currentWeather as an argument
    suggestActivity(currentWeather);

    return 0;  // End the program
}&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;1e59&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Input/Output:&lt;/h2&gt;
&lt;pre class=&quot;routeros&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Enter the weather type (1: Sunny, 2: Cloudy, 3: Rainy, 4: Snowy): 3
It's rainy. Stay indoors and read a book.&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;2e1d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;Explanation:&lt;/h2&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e979&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;We define an&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;called&lt;span&gt;&amp;nbsp;&lt;/span&gt;Weather&lt;span&gt;&amp;nbsp;&lt;/span&gt;with explicit values for each weather type.&lt;/li&gt;
&lt;li id=&quot;b93f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The user inputs a number (1&amp;ndash;4), which is cast to the&lt;span&gt;&amp;nbsp;&lt;/span&gt;Weather&lt;span&gt;&amp;nbsp;&lt;/span&gt;type using&lt;span&gt;&amp;nbsp;&lt;/span&gt;static_cast.&lt;/li&gt;
&lt;li id=&quot;7222&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;static_cast&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a type of&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;type casting&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;in C++. It is used to explicitly convert one data type to another. It is a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;compile-time cast&lt;/b&gt;, meaning the conversion is checked at compile time, and it is generally considered safe for well-defined conversions.&lt;/li&gt;
&lt;li id=&quot;b1ef&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The&lt;span&gt;&amp;nbsp;&lt;/span&gt;switch&lt;span&gt;&amp;nbsp;&lt;/span&gt;statement uses the&lt;span&gt;&amp;nbsp;&lt;/span&gt;Weather&lt;span&gt;&amp;nbsp;&lt;/span&gt;value to suggest an activity.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;c398&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Why Do We Need&lt;span&gt;&amp;nbsp;&lt;/span&gt;static_cast?&lt;/h1&gt;
&lt;p id=&quot;8342&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In the context of the program, we use&lt;span&gt;&amp;nbsp;&lt;/span&gt;static_cast&lt;span&gt;&amp;nbsp;&lt;/span&gt;to convert an&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;integer&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(entered by the user) into an&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;enum&lt;/b&gt;&lt;b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;value&lt;/b&gt;. Here&amp;rsquo;s why this is necessary:&lt;/p&gt;
&lt;p id=&quot;1e98&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;User Input is an Integer&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;0aaf&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;When the user enters a number (e.g.,&lt;span&gt;&amp;nbsp;&lt;/span&gt;1,&lt;span&gt;&amp;nbsp;&lt;/span&gt;2,&lt;span&gt;&amp;nbsp;&lt;/span&gt;3, or&lt;span&gt;&amp;nbsp;&lt;/span&gt;4), it is stored as an integer (int).&lt;/li&gt;
&lt;li id=&quot;ffc4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;However, the program expects a value of type&lt;span&gt;&amp;nbsp;&lt;/span&gt;Weather&lt;span&gt;&amp;nbsp;&lt;/span&gt;(which is an&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum).&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;3cff&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;enum&lt;/b&gt;&lt;b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Values are Not Directly Compatible with Integers&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;583c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Even though&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;values are internally represented as integers, the compiler treats them as a distinct type.&lt;/li&gt;
&lt;li id=&quot;83d8&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;You cannot directly assign an integer to an&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;variable without an explicit cast.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;22e6&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;static_cast&lt;/b&gt;&lt;b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Ensures Safe Conversion&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;8beb&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;static_cast&lt;span&gt;&amp;nbsp;&lt;/span&gt;tells the compiler to treat the integer as a&lt;span&gt;&amp;nbsp;&lt;/span&gt;Weather&lt;span&gt;&amp;nbsp;&lt;/span&gt;type.&lt;/li&gt;
&lt;li id=&quot;cb76&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;This ensures that the conversion is valid and prevents potential errors.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;5aee&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;How Does&lt;span&gt;&amp;nbsp;&lt;/span&gt;static_cast&lt;span&gt;&amp;nbsp;&lt;/span&gt;Work?&lt;/h1&gt;
&lt;p id=&quot;a968&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The syntax for&lt;span&gt;&amp;nbsp;&lt;/span&gt;static_cast&lt;span&gt;&amp;nbsp;&lt;/span&gt;is:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;static_cast&amp;lt;NewType&amp;gt;(expression)&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;4186&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;NewType&lt;/b&gt;: The type you want to convert the expression to.&lt;/li&gt;
&lt;li id=&quot;51d9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;expression&lt;/b&gt;: The value or variable you want to convert.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;9744&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In the program:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;currentWeather = static_cast&amp;lt;Weather&amp;gt;(input);&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;dadc&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Weather&lt;/b&gt;: The target type (the&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;we defined).&lt;/li&gt;
&lt;li id=&quot;763a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;input&lt;/b&gt;: The integer entered by the user.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;c342&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;This line converts the integer&lt;span&gt;&amp;nbsp;&lt;/span&gt;input&lt;span&gt;&amp;nbsp;&lt;/span&gt;into a&lt;span&gt;&amp;nbsp;&lt;/span&gt;Weather&lt;span&gt;&amp;nbsp;&lt;/span&gt;type and assigns it to the variable&lt;span&gt;&amp;nbsp;&lt;/span&gt;currentWeather.&lt;/p&gt;
&lt;h1 id=&quot;0940&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;5. Key Points to Remember&lt;/h1&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;092a&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Always use the&lt;span&gt;&amp;nbsp;&lt;/span&gt;break&lt;span&gt;&amp;nbsp;&lt;/span&gt;statement in&lt;span&gt;&amp;nbsp;&lt;/span&gt;switch&lt;span&gt;&amp;nbsp;&lt;/span&gt;cases to avoid unintended fall-through execution.&lt;/li&gt;
&lt;li id=&quot;c29d&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Use the&lt;span&gt;&amp;nbsp;&lt;/span&gt;default&lt;span&gt;&amp;nbsp;&lt;/span&gt;case as a fallback for unhandled cases.&lt;/li&gt;
&lt;li id=&quot;f2b1&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Enumerators in&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;can be assigned custom values.&lt;/li&gt;
&lt;li id=&quot;e856&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Use&lt;span&gt;&amp;nbsp;&lt;/span&gt;static_cast&lt;span&gt;&amp;nbsp;&lt;/span&gt;to safely convert integers to&lt;span&gt;&amp;nbsp;&lt;/span&gt;enum&lt;span&gt;&amp;nbsp;&lt;/span&gt;values when required.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>cpp beginner</category>
      <category>cpp programming</category>
      <category>Enum</category>
      <category>switch statement</category>
      <category>type casting in cpp</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/52</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp018-Switch-and-Enum-in-C#entry52comment</comments>
      <pubDate>Sat, 5 Apr 2025 19:55:13 +0900</pubDate>
    </item>
    <item>
      <title>Cpp_017: Range-Based For Loops in C++</title>
      <link>https://codeaddict.tistory.com/entry/Cpp017-Range-Based-For-Loops-in-C</link>
      <description>&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p id=&quot;0154&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Range-based for loops, introduced in&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;C++11&lt;/b&gt;, provide a clean and concise way to iterate over elements in a container (like arrays, vectors, or strings) without needing explicit indices or iterators. They simplify code and make it more readable, especially for beginners. In this tutorial, we&amp;rsquo;ll explore the syntax, provide examples, and solve common problems to help you master this powerful feature.&lt;/p&gt;
&lt;h1 id=&quot;addf&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;1. Syntax of Range-Based For Loops&lt;/h1&gt;
&lt;p id=&quot;b9e2&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;The basic syntax is:&lt;/p&gt;
&lt;pre class=&quot;elm&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;for (type variable : container) {
    // Code block
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;c551&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Explanation of Syntax&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c8ad&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;type&lt;/b&gt;: The data type of the elements in the container (e.g.,&lt;span&gt;&amp;nbsp;&lt;/span&gt;int,&lt;span&gt;&amp;nbsp;&lt;/span&gt;char,&lt;span&gt;&amp;nbsp;&lt;/span&gt;std::string).&lt;/li&gt;
&lt;li id=&quot;49ea&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;variable&lt;/b&gt;: A variable that takes the value of each element in the container, one at a time.&lt;/li&gt;
&lt;li id=&quot;d5a2&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;container&lt;/b&gt;: An iterable object like an array, vector, or string.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;6af0&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;You can also use&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;references (&lt;/b&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;to modify elements directly or&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;auto&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;for automatic type deduction.&lt;/p&gt;
&lt;pre class=&quot;groovy&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;for (int x : arr) {
    // Code block
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;a3ae&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example of Syntax Usage (In Code)&lt;/h1&gt;
&lt;p id=&quot;82fb&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s how the above analogy translates into code:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;  // Add this line to avoid writing std::

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

    // Range-based for loop
    for (int x : arr) {
        cout &amp;lt;&amp;lt; x &amp;lt;&amp;lt; &quot; &quot;;  // Output: 1 2 3 4 5
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;6981&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2. Examples of Range-Based For Loops&lt;/h1&gt;
&lt;h1 id=&quot;565f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example 1: Iterating Over an Array&lt;/h1&gt;
&lt;p id=&quot;b7dc&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s start with a simple example of iterating over an array of integers.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;  // Add this line

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

    // Range-based for loop
    for (int x : arr) {
        cout &amp;lt;&amp;lt; x &amp;lt;&amp;lt; &quot; &quot;;  // Output: 1 2 3 4 5
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;b801&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;c99f&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;int x&lt;span&gt;&amp;nbsp;&lt;/span&gt;represents each element in the array&lt;span&gt;&amp;nbsp;&lt;/span&gt;arr.&lt;/li&gt;
&lt;li id=&quot;60cf&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The loop automatically iterates over all elements in the array and prints them.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;85c7&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example 2: Using a Vector&lt;/h1&gt;
&lt;p id=&quot;1786&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Now, let&amp;rsquo;s iterate over a&lt;span&gt;&amp;nbsp;&lt;/span&gt;std::vector&lt;span&gt;&amp;nbsp;&lt;/span&gt;of integers.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;  // Add this line

int main() {
    vector&amp;lt;int&amp;gt; vec = {10, 20, 30};

    // Range-based for loop
    for (int x : vec) {
        cout &amp;lt;&amp;lt; x &amp;lt;&amp;lt; &quot; &quot;;  // Output: 10 20 30
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;981a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e9cb&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The range-based for loop works seamlessly with&lt;span&gt;&amp;nbsp;&lt;/span&gt;vector.&lt;/li&gt;
&lt;li id=&quot;b257&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;It&amp;rsquo;s a great way to process collections without worrying about indices.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;c2ef&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Example 3: Modifying Elements with References&lt;/h1&gt;
&lt;p id=&quot;c041&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;You can use references (&amp;amp;) to modify elements directly in the container.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;  // Add this line

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

    // Range-based for loop with reference
    for (int&amp;amp; x : arr) {
        x *= 2;  // Double each element
    }

    // Print modified array
    for (int x : arr) {
        cout &amp;lt;&amp;lt; x &amp;lt;&amp;lt; &quot; &quot;;  // Output: 2 4 6
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;8845&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;5b7b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;int&amp;amp; x&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a reference to each element in the array.&lt;/li&gt;
&lt;li id=&quot;6dc3&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Modifying&lt;span&gt;&amp;nbsp;&lt;/span&gt;x&lt;span&gt;&amp;nbsp;&lt;/span&gt;directly changes the original array elements.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;7cba&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;3. Practical Applications&lt;/h1&gt;
&lt;p id=&quot;aaaf&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Range-based for loops are ideal for:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;82f5&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Iterating over containers without needing indices.&lt;/li&gt;
&lt;li id=&quot;ac26&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Processing strings, arrays, or collections cleanly.&lt;/li&gt;
&lt;li id=&quot;78c9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Simplifying code when index access isn&amp;rsquo;t required.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;ed4e&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;However, they are less flexible than traditional loops (e.g., you can&amp;rsquo;t easily reverse iterate or skip elements).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;2c11&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;4. Problems and Solutions&lt;/h1&gt;
&lt;h1 id=&quot;45a0&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Problem 1: Print All Characters in a String&lt;/h1&gt;
&lt;p id=&quot;009e&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Task:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Print each character of the string&lt;span&gt;&amp;nbsp;&lt;/span&gt;&quot;Hello&quot;&lt;span&gt;&amp;nbsp;&lt;/span&gt;separated by a space.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
using namespace std;  // Add this line

int main() {
    string str = &quot;Hello&quot;;

    // Range-based for loop
    for (char c : str) {
        cout &amp;lt;&amp;lt; c &amp;lt;&amp;lt; &quot; &quot;;  // Output: H e l l o
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;76ba&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Problem 2: Calculate the Sum of Elements in an Array&lt;/h1&gt;
&lt;p id=&quot;fb78&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Task:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Calculate the sum of elements in the array&lt;span&gt;&amp;nbsp;&lt;/span&gt;{1, 2, 3, 4, 5}.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;  // Add this line

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

    // Range-based for loop
    for (int x : arr) {
        sum += x;
    }

    cout &amp;lt;&amp;lt; sum;  // Output: 15
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;cfe6&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Problem 3: Reverse-Print a Vector&lt;/h1&gt;
&lt;p id=&quot;f7e1&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Task:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Print the elements of the vector&lt;span&gt;&amp;nbsp;&lt;/span&gt;{10, 20, 30}&lt;span&gt;&amp;nbsp;&lt;/span&gt;in reverse order.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;  // Add this line

int main() {
    vector&amp;lt;int&amp;gt; vec = {10, 20, 30};

    // Use reverse iterators
    for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
        cout &amp;lt;&amp;lt; *it &amp;lt;&amp;lt; &quot; &quot;;  // Output: 30 20 10
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;bbcd&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;1039&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Range-based for loops don&amp;rsquo;t natively support reverse iteration.&lt;/li&gt;
&lt;li id=&quot;beba&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;We use reverse iterators (rbegin()&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;rend()) as a workaround.&lt;/li&gt;
&lt;li id=&quot;3186&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;For a deeper understanding of&lt;span&gt;&amp;nbsp;&lt;/span&gt;rbegin()&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;rend(), refer to the end of this tutorial. ====&amp;gt;&amp;gt;&amp;gt;&amp;gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;13a4&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;5. Key Takeaways&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;4581&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Range-based for loops are&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;clean and concise&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;for iterating over containers.&lt;/li&gt;
&lt;li id=&quot;5619&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;They are&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;ideal for simple traversals&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;but lack the flexibility of traditional loops.&lt;/li&gt;
&lt;li id=&quot;b910&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Use&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;references (&lt;/b&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;to modify elements directly.&lt;/li&gt;
&lt;li id=&quot;7bc7&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;For reverse iteration, use&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;reverse iterators&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;92c1&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;6. Challenge for Readers&lt;/h1&gt;
&lt;p id=&quot;3996&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Problem:&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;Write a program that uses a range-based for loop to count how many times the letter&lt;span&gt;&amp;nbsp;&lt;/span&gt;'a'&lt;span&gt;&amp;nbsp;&lt;/span&gt;appears in the string&lt;span&gt;&amp;nbsp;&lt;/span&gt;&quot;banana&quot;.&lt;/p&gt;
&lt;p id=&quot;5918&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
using namespace std;

int main() {
    string str = &quot;banana&quot;;
    int count = 0;

    for (char c : str) {
        if (c == 'a') {
            count++;
        }
    }

    cout &amp;lt;&amp;lt; &quot;The letter 'a' appears &quot; &amp;lt;&amp;lt; count &amp;lt;&amp;lt; &quot; times.&quot; &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;bf34&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;bash&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;The letter 'a' appears 3 times.&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;c6b0&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;====&amp;gt;&lt;/p&gt;
&lt;p id=&quot;cea1&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;To understand how reverse iterators like&lt;span&gt;&amp;nbsp;&lt;/span&gt;rbegin()&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;rend()&lt;span&gt;&amp;nbsp;&lt;/span&gt;work, refer to the detailed explanation at the end of this tutorial.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;6ad7&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;What Are Iterators?&lt;/h1&gt;
&lt;p id=&quot;f03f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Iterators are like&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;pointers&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;that help you traverse (move through) the elements of a container (e.g., an array, vector, or string). They provide a way to access elements without needing to know the underlying structure of the container.&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;0bf9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Normal Iterators&lt;/b&gt;: Move from the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;beginning&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;to the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;end&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;of the container.&lt;/li&gt;
&lt;li id=&quot;33ec&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Reverse Iterators&lt;/b&gt;: Move from the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;end&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;to the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;beginning&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;of the container.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;7b1d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;What Are&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.rbegin()&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.rend()?&lt;/h1&gt;
&lt;h1 id=&quot;4b88&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;1.&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.rbegin()&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;22c4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Full Name&lt;/b&gt;: Reverse Begin Iterator.&lt;/li&gt;
&lt;li id=&quot;2b79&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;What It Does&lt;/b&gt;: It points to the&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;last element&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;of the container.&lt;/li&gt;
&lt;li id=&quot;29bf&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;How It Works&lt;/b&gt;: When you use&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.rbegin(), you&amp;rsquo;re asking for an iterator that starts at the end of the vector and moves backward.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;8b45&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;2.&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.rend()&lt;/h1&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;2ced&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Full Name&lt;/b&gt;: Reverse End Iterator.&lt;/li&gt;
&lt;li id=&quot;8d21&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;What It Does&lt;/b&gt;: It points to&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;one position before the first element&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;of the container (essentially, the &amp;ldquo;end&amp;rdquo; of the reverse iteration).&lt;/li&gt;
&lt;li id=&quot;6c8a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;How It Works&lt;/b&gt;: When you use&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.rend(), you&amp;rsquo;re asking for an iterator that marks the stopping point for reverse iteration.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;2854&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Visual Representation&lt;/h1&gt;
&lt;p id=&quot;1e5a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s say you have a vector:&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;vector&amp;lt;int&amp;gt; vec = {10, 20, 30};&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;14e4&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s how the elements are stored in memory:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Index:   0    1    2
Value:  10   20   30&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;172e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Normal Iterators&lt;/b&gt;:&lt;/li&gt;
&lt;li id=&quot;6107&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;vec.begin()&lt;span&gt;&amp;nbsp;&lt;/span&gt;points to&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;10&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(index 0).&lt;/li&gt;
&lt;li id=&quot;03fc&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;vec.end()&lt;span&gt;&amp;nbsp;&lt;/span&gt;points to&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;one position after 30&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(index 3).&lt;/li&gt;
&lt;li id=&quot;a3be&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Reverse Iterators&lt;/b&gt;:&lt;/li&gt;
&lt;li id=&quot;c27c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;vec.rbegin()&lt;span&gt;&amp;nbsp;&lt;/span&gt;points to&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;30&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(index 2).&lt;/li&gt;
&lt;li id=&quot;d220&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;vec.rend()&lt;span&gt;&amp;nbsp;&lt;/span&gt;points to&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;one position before 10&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(index -1).&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;ad46&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;How Reverse Iterators Work&lt;/h1&gt;
&lt;p id=&quot;e5ce&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;When you use a reverse iterator, it moves&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;backward&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;through the container. Here&amp;rsquo;s how the loop works:&lt;/p&gt;
&lt;pre class=&quot;livescript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
    cout &amp;lt;&amp;lt; *it &amp;lt;&amp;lt; &quot; &quot;;  // Output: 30 20 10
}&lt;/code&gt;&lt;/pre&gt;
&lt;h1 id=&quot;4484&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Step-by-Step Breakdown&lt;/h1&gt;
&lt;p id=&quot;90ab&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Initialization&lt;/b&gt;:&lt;span&gt;&amp;nbsp;&lt;/span&gt;auto it = vec.rbegin()&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;df1d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;it&lt;span&gt;&amp;nbsp;&lt;/span&gt;starts at the last element (30).&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;482f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Condition&lt;/b&gt;:&lt;span&gt;&amp;nbsp;&lt;/span&gt;it != vec.rend()&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;1577&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The loop continues as long as&lt;span&gt;&amp;nbsp;&lt;/span&gt;it&lt;span&gt;&amp;nbsp;&lt;/span&gt;hasn&amp;rsquo;t reached&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.rend()&lt;span&gt;&amp;nbsp;&lt;/span&gt;(one position before the first element).&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;6623&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Increment&lt;/b&gt;:&lt;span&gt;&amp;nbsp;&lt;/span&gt;++it&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;4abc&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Since this is a reverse iterator,&lt;span&gt;&amp;nbsp;&lt;/span&gt;++it&lt;span&gt;&amp;nbsp;&lt;/span&gt;moves&lt;span&gt;&amp;nbsp;&lt;/span&gt;it&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;backward&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;to the previous element.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;169c&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Dereference&lt;/b&gt;:&lt;span&gt;&amp;nbsp;&lt;/span&gt;*it&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;b56e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;*it&lt;span&gt;&amp;nbsp;&lt;/span&gt;gives the value of the element currently pointed to by&lt;span&gt;&amp;nbsp;&lt;/span&gt;it.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>cpp iterator</category>
      <category>cpp vector</category>
      <category>range based for loops</category>
      <category>rbegin</category>
      <category>reverse iterators</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/51</guid>
      <comments>https://codeaddict.tistory.com/entry/Cpp017-Range-Based-For-Loops-in-C#entry51comment</comments>
      <pubDate>Sat, 5 Apr 2025 19:53:45 +0900</pubDate>
    </item>
    <item>
      <title>cpp_016: Comparing C-Style Arrays, std::array, and std::vector in C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp016-Comparing-C-Style-Arrays-stdarray-and-stdvector-in-C</link>
      <description>&lt;h2 id=&quot;dfd7&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;1- Introduction&lt;/h2&gt;
&lt;p id=&quot;ec1e&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In previous tutorials, we explored different ways to handle collections in C++. We started with traditional&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;C-style arrays&lt;/b&gt;, then introduced the dynamic&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;std::vector&lt;/b&gt;, and most recently discussed the modern&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;std::array&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;in&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;a style=&quot;color: #000000;&quot; href=&quot;https://example.com/cpp_015-stl-array&quot;&gt;cpp_015: STL Array in C++&lt;/a&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(&lt;a href=&quot;https://medium.com/@staytechrich/list/cpp-c-beginner-053ab9a0ecc3&quot;&gt;https://medium.com/@staytechrich/list/cpp-c-beginner-053ab9a0ecc3&lt;/a&gt;).&lt;/p&gt;
&lt;p id=&quot;78ba&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;We also examined how these types are passed to functions: C-style arrays as pointers, std::array as objects (by value or reference), and std::vector typically by reference to avoid copying.&lt;/p&gt;
&lt;p id=&quot;184c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Now, it&amp;rsquo;s time to tie it all together! In this tutorial, we&amp;rsquo;ll:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;a60b&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Summarize the key differences between C-style arrays, std::array, and std::vector.&lt;/li&gt;
&lt;li id=&quot;222a&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Show examples highlighting these differences.&lt;/li&gt;
&lt;li id=&quot;b1f3&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Provide an integrated example using all three in one program.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;ddf0&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size26&quot;&gt;2- Key Differences with Integrated Examples&lt;/h2&gt;
&lt;p id=&quot;30ea&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2.1 Size&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;e58e&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;C-style array&lt;/b&gt;: Fixed, no built-in size method, but size can be calculated with sizeof(arr) / sizeof(arr[0]) in the defining scope.&lt;/li&gt;
&lt;li id=&quot;83c9&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::array&lt;/b&gt;: Fixed, knows its size via .size().&lt;/li&gt;
&lt;li id=&quot;e419&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::vector&lt;/b&gt;: Dynamic, resizes at runtime.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;b0b8&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;array&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    int cstyle[3] = {1, 2, 3};           // Fixed, size calculable in scope
    array&amp;lt;int, 3&amp;gt; stlarr = {4, 5, 6};   // Fixed, has .size()
    vector&amp;lt;int&amp;gt; vec = {7, 8, 9};        // Dynamic

    // Calculate size for C-style array
    int cstyleSize = sizeof(cstyle) / sizeof(cstyle[0]);
    cout &amp;lt;&amp;lt; &quot;C-style size: &quot; &amp;lt;&amp;lt; cstyleSize &amp;lt;&amp;lt; &quot; (calculated with sizeof)\n&quot;;
    cout &amp;lt;&amp;lt; &quot;std::array size: &quot; &amp;lt;&amp;lt; stlarr.size() &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;std::vector size: &quot; &amp;lt;&amp;lt; vec.size() &amp;lt;&amp;lt; endl;

    vec.push_back(10); // Vector grows
    cout &amp;lt;&amp;lt; &quot;std::vector size after push_back: &quot; &amp;lt;&amp;lt; vec.size() &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;df4c&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;C-style size: 3 (calculated with sizeof)
std::array size: 3
std::vector size: 3
std::vector size after push_back: 4&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;3aed&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2.2 Safety&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;6454&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;C-style array&lt;/b&gt;: No bounds checking.&lt;/li&gt;
&lt;li id=&quot;50ad&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::array&lt;/b&gt;: .at() checks bounds.&lt;/li&gt;
&lt;li id=&quot;af70&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::vector&lt;/b&gt;: .at() checks bounds.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;0825&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;array&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    int cstyle[3] = {1, 2, 3};
    array&amp;lt;int, 3&amp;gt; stlarr = {4, 5, 6};
    vector&amp;lt;int&amp;gt; vec = {7, 8, 9};

    cout &amp;lt;&amp;lt; &quot;C-style at 5: &quot; &amp;lt;&amp;lt; cstyle[5] &amp;lt;&amp;lt; endl; // Undefined behavior

    try {
        cout &amp;lt;&amp;lt; &quot;std::array at 5: &quot; &amp;lt;&amp;lt; stlarr.at(5) &amp;lt;&amp;lt; endl;
    } catch (const out_of_range&amp;amp; e) {
        cout &amp;lt;&amp;lt; &quot;std::array error: &quot; &amp;lt;&amp;lt; e.what() &amp;lt;&amp;lt; endl;
    }

    try {
        cout &amp;lt;&amp;lt; &quot;std::vector at 5: &quot; &amp;lt;&amp;lt; vec.at(5) &amp;lt;&amp;lt; endl;
    } catch (const out_of_range&amp;amp; e) {
        cout &amp;lt;&amp;lt; &quot;std::vector error: &quot; &amp;lt;&amp;lt; e.what() &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;f1ae&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;(varies for C-style, random value or crash):&lt;/p&gt;
&lt;pre class=&quot;maxima&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;C-style at 5: 32764
ERROR!
std::array at 5: std::array error: array::at: __n (which is 5) &amp;gt;= _Nm (which is 3)
std::vector at 5: std::vector error: vector::_M_range_check: __n (which is 5) &amp;gt;= this-&amp;gt;size() (which is 3)&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;2160&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2.3 Flexibility&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;43a6&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;C-style array&lt;/b&gt;: Static, no resizing.&lt;/li&gt;
&lt;li id=&quot;a828&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::array&lt;/b&gt;: Static, fixed size.&lt;/li&gt;
&lt;li id=&quot;4fdd&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::vector&lt;/b&gt;: Dynamic, can grow/shrink.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;array&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    int cstyle[3] = {1, 2, 3};         // Cannot resize
    array&amp;lt;int, 3&amp;gt; stlarr = {4, 5, 6}; // Cannot resize
    vector&amp;lt;int&amp;gt; vec = {7, 8, 9};      // Can resize

    // Print initial values
    cout &amp;lt;&amp;lt; &quot;C-style: &quot;; for (int i = 0; i &amp;lt; 3; i++) cout &amp;lt;&amp;lt; cstyle[i] &amp;lt;&amp;lt; &quot; &quot;;
    cout &amp;lt;&amp;lt; &quot;\nstd::array: &quot;; for (int i = 0; i &amp;lt; 3; i++) cout &amp;lt;&amp;lt; stlarr[i] &amp;lt;&amp;lt; &quot; &quot;;
    cout &amp;lt;&amp;lt; &quot;\nstd::vector: &quot;; for (int i = 0; i &amp;lt; 3; i++) cout &amp;lt;&amp;lt; vec[i] &amp;lt;&amp;lt; &quot; &quot;;

    vec.push_back(10); // Only vector can grow
    cout &amp;lt;&amp;lt; &quot;\nstd::vector after push_back: &quot;;
    for (int i = 0; i &amp;lt; vec.size(); i++) cout &amp;lt;&amp;lt; vec[i] &amp;lt;&amp;lt; &quot; &quot;;
    cout &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;067a&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;C-style: 1 2 3 
std::array: 4 5 6 
std::vector: 7 8 9 
std::vector after push_back: 7 8 9 10 &lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;768f&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2.4 Performance&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;02f4&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;C-style array&lt;/b&gt;: Fastest (no overhead).&lt;/li&gt;
&lt;li id=&quot;7084&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::array&lt;/b&gt;: Nearly as fast.&lt;/li&gt;
&lt;li id=&quot;0a36&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::vector&lt;/b&gt;: Slightly slower due to dynamic management.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;68d2&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2.5 Function Passing&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc; background-color: #ffffff; color: #000000; text-align: start;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;8d04&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;C-style array&lt;/b&gt;: Passed as a pointer.&lt;/li&gt;
&lt;li id=&quot;385c&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::array&lt;/b&gt;: Passed by value or reference.&lt;/li&gt;
&lt;li id=&quot;da8d&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;std::vector&lt;/b&gt;: Passed by reference.&lt;/li&gt;
&lt;/ul&gt;
&lt;p id=&quot;d693&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;array&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int sumCStyle(int arr[], int size) {
    int sum = 0;
    for (int i = 0; i &amp;lt; size; i++) sum += arr[i];
    return sum;
}

int sumSTLArray(const array&amp;lt;int, 3&amp;gt;&amp;amp; arr) {
    int sum = 0;
    for (int i = 0; i &amp;lt; arr.size(); i++) sum += arr[i];
    return sum;
}

int sumVector(const vector&amp;lt;int&amp;gt;&amp;amp; vec) {
    int sum = 0;
    for (int i = 0; i &amp;lt; vec.size(); i++) sum += vec[i];
    return sum;
}

int main() {
    int cstyle[3] = {85, 90, 95};
    array&amp;lt;int, 3&amp;gt; stlarr = {88, 92, 87};
    vector&amp;lt;int&amp;gt; vec = {90, 85, 95};
    vec.push_back(88); // Dynamic growth

    cout &amp;lt;&amp;lt; &quot;C-style sum: &quot; &amp;lt;&amp;lt; sumCStyle(cstyle, 3) &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;std::array sum: &quot; &amp;lt;&amp;lt; sumSTLArray(stlarr) &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;std::vector sum: &quot; &amp;lt;&amp;lt; sumVector(vec) &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;edcb&quot; style=&quot;background-color: #ffffff; color: #242424; text-align: start;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;maxima&quot; style=&quot;background-color: #f9f9f9; color: #242424; text-align: start;&quot;&gt;&lt;code&gt;C-style sum: 270
std::array sum: 267
std::vector sum: 358&lt;/code&gt;&lt;/pre&gt;</description>
      <category>C++ Beginner</category>
      <category>array</category>
      <category>cpp vector</category>
      <category>STL</category>
      <category>Vector</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/50</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp016-Comparing-C-Style-Arrays-stdarray-and-stdvector-in-C#entry50comment</comments>
      <pubDate>Sat, 5 Apr 2025 19:51:16 +0900</pubDate>
    </item>
    <item>
      <title>cpp_015: STL Array in&amp;nbsp;C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp015-STL-Array-in-C</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Introduction&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The Standard Template Library (STL) array, introduced in C++11, is a fixed-size container that offers a safer and more convenient alternative to traditional C-style arrays. Defined in the &amp;lt;array&amp;gt; header, std::array combines the performance of raw arrays with the benefits of STL containers, such as knowing its own size, bounds checking with certain methods, and compatibility with STL algorithms.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this lesson, we&amp;rsquo;ll cover:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;What std::array is and how it works.&lt;/li&gt;
&lt;li&gt;The syntax for declaring and using std::array.&lt;/li&gt;
&lt;li&gt;Examples of working with std::array, including passing it to functions.&lt;/li&gt;
&lt;li&gt;Two practice problems for you to solve.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The std::array is a container that encapsulates a fixed-size array. Unlike C-style arrays, which are raw pointers to memory and don&amp;rsquo;t carry size information, std::array is a proper object that provides useful member functions like&amp;nbsp;.size(),&amp;nbsp;.at(), and iterators. It&amp;rsquo;s also more type-safe and easier to pass to functions since it behaves like a regular object.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Key features:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Fixed size, specified at compile time.&lt;/li&gt;
&lt;li&gt;Knows its own size (no need to pass it separately).&lt;/li&gt;
&lt;li&gt;Supports STL features like iterators and bounds checking with&amp;nbsp;.at().&lt;/li&gt;
&lt;li&gt;Passed by value or reference to functions.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s explore the syntax and examples to see how it works!&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Syntax for STL&amp;nbsp;Array&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Declaration&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;array&amp;gt;
std::array&amp;lt;T, N&amp;gt; name;&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;T: The data type of the elements (e.g., int, double, char).&lt;/li&gt;
&lt;li&gt;N: The size of the array (must be a constant known at compile time).&lt;/li&gt;
&lt;li&gt;name: The variable name of the array.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Common Member Functions&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;.size(): Returns the number of elements.&lt;/li&gt;
&lt;li&gt;.at(index): Accesses an element with bounds checking (throws an exception if out of bounds).&lt;/li&gt;
&lt;li&gt;[index]: Accesses an element without bounds checking (faster but unsafe if misused).&lt;/li&gt;
&lt;li&gt;.front(): Returns the first element.&lt;/li&gt;
&lt;li&gt;.back(): Returns the last element.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Example of&amp;nbsp;Syntax&lt;/h3&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;array&amp;gt;
using namespace std;

int main() {
    // Declare an STL array of 5 integers
    array&amp;lt;int, 5&amp;gt; arr = {10, 20, 30, 40, 50};

    // Access elements
    cout &amp;lt;&amp;lt; &quot;First element: &quot; &amp;lt;&amp;lt; arr[0] &amp;lt;&amp;lt; endl;         // 10
    cout &amp;lt;&amp;lt; &quot;Element at index 2: &quot; &amp;lt;&amp;lt; arr.at(2) &amp;lt;&amp;lt; endl; // 30
    cout &amp;lt;&amp;lt; &quot;Size of array: &quot; &amp;lt;&amp;lt; arr.size() &amp;lt;&amp;lt; endl;     // 5

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Problems with Old-Style Arrays&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Old-style arrays are basic. You write them like this:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;int numbers[3] = {5, 10, 15};&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;But they have issues:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;No size info&lt;/b&gt;: The array doesn&amp;rsquo;t &amp;ldquo;know&amp;rdquo; how many boxes it has. If you forget the size, you might try to use a box that doesn&amp;rsquo;t exist, causing errors (called &amp;ldquo;out of bounds&amp;rdquo;).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Raw pointers&lt;/b&gt;: When you pass this array to a function, C++ doesn&amp;rsquo;t send the whole row of boxes &amp;mdash; it just sends a &amp;ldquo;pointer&amp;rdquo; (an address in memory) to the first box. This can confuse beginners and lead to mistakes.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;No safety&lt;/b&gt;: If you accidentally ask for numbers[10] (way past the 3 boxes), the program might crash or act weird because there&amp;rsquo;s no check to stop you.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;What Makes STL array&amp;nbsp;Better?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The STL array fixes these problems. It&amp;rsquo;s like a smart row of boxes that:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Knows its size&lt;/b&gt;: You tell it how many boxes it has when you create it, and it remembers that number.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Fixed size&lt;/b&gt;: Once you set the number of boxes (e.g., 5), you can&amp;rsquo;t change it. This makes it predictable and safe.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Safer access&lt;/b&gt;: It has a way to check if you&amp;rsquo;re asking for a box that exists (called &amp;ldquo;bounds checking&amp;rdquo;).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Acts like an object&lt;/b&gt;: You can pass it to functions easily without worrying about pointers.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Simple Example&amp;nbsp;&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Problem Statement&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Write a program that declares an STL array of integers, passes it to a function, and calculates the sum of its elements.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Solution&lt;/h3&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;array&amp;gt;
using namespace std;

// Function to calculate the sum of elements in an STL array
int calculateSum(const array&amp;lt;int, 5&amp;gt;&amp;amp; arr) {  // Passed by const reference for efficiency
    int sum = 0;
    for (int i = 0; i &amp;lt; arr.size(); i++) {
        sum += arr[i];
    }
    return sum;
}

int main() {
    // Declare and initialize an STL array
    array&amp;lt;int, 5&amp;gt; numbers = {1, 2, 3, 4, 5};

    // Pass the array to the function
    int result = calculateSum(numbers);

    cout &amp;lt;&amp;lt; &quot;The sum of the array elements is: &quot; &amp;lt;&amp;lt; result &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output&lt;/h3&gt;
&lt;pre class=&quot;smali&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;The sum of the array elements is: 15&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Practice Problems&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Problem 1: Finding the Minimum&amp;nbsp;Element&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Task&lt;/b&gt;: Write a program that:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Creates an STL array of 6 doubles.&lt;/li&gt;
&lt;li&gt;Passes it to a function that finds the smallest number.&lt;/li&gt;
&lt;li&gt;Prints the result in main().&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Hint&lt;/b&gt;: Loop through and compare each item to find the smallest.&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;array&amp;gt;
using namespace std;

double findMin(const array&amp;lt;double, 6&amp;gt;&amp;amp; arr) {
    double min = arr[0];
    for (int i = 1; i &amp;lt; arr.size(); i++) {
        if (arr[i] &amp;lt; min) {
            min = arr[i];
        }
    }
    return min;
}

int main() {
    array&amp;lt;double, 6&amp;gt; numbers = {3.5, 1.2, 4.8, 0.9, 2.7, 5.1};
    double result = findMin(numbers);
    cout &amp;lt;&amp;lt; &quot;Smallest number: &quot; &amp;lt;&amp;lt; result &amp;lt;&amp;lt; endl; // Prints 0.9
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Problem 2: Reversing an STL&amp;nbsp;Array&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Task&lt;/b&gt;: Write a program that:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Creates an STL array of 4 characters (e.g., {&amp;lsquo;A&amp;rsquo;, &amp;lsquo;B&amp;rsquo;, &amp;lsquo;C&amp;rsquo;, &amp;lsquo;D&amp;rsquo;}).&lt;/li&gt;
&lt;li&gt;Passes it to a function that reverses it (e.g., to {&amp;lsquo;D&amp;rsquo;, &amp;lsquo;C&amp;rsquo;, &amp;lsquo;B&amp;rsquo;, &amp;lsquo;A&amp;rsquo;}).&lt;/li&gt;
&lt;li&gt;Prints the reversed array in main().&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Hint&lt;/b&gt;: Swap items from the start and end, moving inward.&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;array&amp;gt;
using namespace std;

void reverseArray(array&amp;lt;char, 4&amp;gt;&amp;amp; arr) {
    for (int i = 0; i &amp;lt; arr.size() / 2; i++) {
        char temp = arr[i];
        arr[i] = arr[arr.size() - 1 - i];
        arr[arr.size() - 1 - i] = temp;
    }
}

int main() {
    array&amp;lt;char, 4&amp;gt; letters = {'A', 'B', 'C', 'D'};
    reverseArray(letters);
    cout &amp;lt;&amp;lt; &quot;Reversed array: &quot;;
    for (int i = 0; i &amp;lt; letters.size(); i++) {
        cout &amp;lt;&amp;lt; letters[i] &amp;lt;&amp;lt; &quot; &quot;; // Prints D C B A
    }
    cout &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Here&amp;rsquo;s how it works step by&amp;nbsp;step:&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Swapping Logic&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;You start by swapping the element at index 0 with the element at the last index arr.size() - 1.&lt;/li&gt;
&lt;li&gt;Then, you swap the element at index 1 with the second-to-last element at index arr.size() - 2, and so on.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Why only go up to half?&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;When you swap the element at index i with the element at index arr.size() - 1 - i, you're already taking care of two positions: i and arr.size() - 1 - i.&lt;/li&gt;
&lt;li&gt;After the first swap, the first and last elements are reversed. After the second swap, the second and second-to-last elements are reversed, and so on.&lt;/li&gt;
&lt;li&gt;If you continued swapping beyond arr.size() / 2, you'd essentially start swapping elements that have already been swapped.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Example&lt;/b&gt;: If the array has 4 elements, say: arr = ['a', 'b', 'c', 'd']:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;First iteration&lt;/b&gt;: Swap arr[0] and arr[3] &amp;rarr; arr = ['d', 'b', 'c', 'a']&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Second iteration&lt;/b&gt;: Swap arr[1] and arr[2] &amp;rarr; arr = ['d', 'c', 'b', 'a']&lt;/li&gt;
&lt;li&gt;Now the array is fully reversed, and there&amp;rsquo;s no need to swap further.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this case, the loop only needs to run twice (i = 0 and i = 1), which is half the size of the array.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>bounds checking</category>
      <category>C++ 프로그래밍</category>
      <category>C++11</category>
      <category>fixed-size array</category>
      <category>Standard Template Library</category>
      <category>stl array</category>
      <category>stl 배열</category>
      <category>고정 크기 배열</category>
      <category>표준 템플릿 라이브러리</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/49</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp015-STL-Array-in-C#entry49comment</comments>
      <pubDate>Mon, 10 Mar 2025 20:41:20 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_008: Understanding Generators in&amp;nbsp;Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate008-Understanding-Generators-in-Python</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In our previous tutorial (&lt;a href=&quot;https://codeaddict.tistory.com/entry/Python-Intermediate007-Understanding-property-and-Setter-Decorators-in-Python&quot; target=&quot;_blank&quot; rel=&quot;noopener&amp;nbsp;noreferrer&quot;&gt;https://codeaddict.tistory.com/entry/Python-Intermediate007-Understanding-property-and-Setter-Decorators-in-Python&lt;/a&gt;), we explored how to use @property and @&amp;lt;property_name&amp;gt;.setter to manage class attributes. Today, we&amp;rsquo;ll dive into &lt;b&gt;generators&lt;/b&gt; in Python, a powerful tool for creating iterators in a memory-efficient way. We&amp;rsquo;ll cover the basics, syntax, and practical examples, and end with some problems for you to solve!&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1- What Are Generators?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Generators are a special type of function in Python that allow you to iterate over a sequence of values without storing the entire sequence in memory. They are particularly useful when working with large datasets or infinite sequences.&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Generator Function&lt;/b&gt;: A function that uses yield to return values one at a time, pausing its state between calls, instead of returning a list or all values at once.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Generator Expression&lt;/b&gt;: A compact, memory-efficient alternative to list comprehensions, using parentheses (&amp;hellip;) instead of brackets [&amp;hellip;].&lt;/li&gt;
&lt;li&gt;Unlike regular functions that return all data at once, generators produce values on-demand, making them ideal for lazy evaluation.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Key Features&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Lazy Evaluation: Values are generated on-the-fly, one at a time.&lt;/li&gt;
&lt;li&gt;Memory Efficiency: Only one value is stored in memory at a time.&lt;/li&gt;
&lt;li&gt;Use yield instead of return to produce a sequence of values.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2- Syntax and Execution Order&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2&amp;ndash;1 Syntax&lt;/h3&gt;
&lt;pre class=&quot;ruby&quot; data-code-block-lang=&quot;ruby&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;def my_generator():
    yield 1
    yield 2
    yield 3&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;yield&lt;/b&gt;: Pauses the function and returns a value to the caller. The function resumes from where it left off when next called.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Execution Order&lt;/b&gt;:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;When the generator function is called, it returns a generator object (but doesn&amp;rsquo;t start execution).&lt;/li&gt;
&lt;li&gt;The generator runs until it hits a yield statement, then pauses and returns the yielded value.&lt;/li&gt;
&lt;li&gt;On the next call, it resumes execution from where it paused.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Example: Simple Generator&lt;/h3&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;def simple_generator():
    yield &quot;Python&quot;
    yield &quot;Generators&quot;
    yield &quot;Are&quot;
    yield &quot;Awesome&quot;

# Create a generator object
gen = simple_generator()
# Iterate through the generator
for word in gen:
    print(word)&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;ebnf&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Python
Generators
Are
Awesome&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2&amp;ndash;2 Execution Order with one&amp;nbsp;example&lt;/h3&gt;
&lt;pre class=&quot;properties&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;# Generator Function
def my_generator():
    n = 0
    while n &amp;lt; 3:
        yield n
        n += 1

# Generator Expression
gen_expr = (x * 2 for x in range(5))

# Usage
gen = my_generator()
for value in gen:
    print(value)  # Prints 0, 1, 2&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Generator Function&lt;/b&gt;: Uses yield to produce a value and suspend execution until the next call (e.g., via a next() or loop).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Generator Expression&lt;/b&gt;: Similar to list comprehensions but generates values lazily.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Execution Order&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Function Definition&lt;/b&gt;: The generator function is defined, but no code runs until called.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Generator Creation&lt;/b&gt;: Calling my_generator() returns a generator object without executing the body.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Value Generation&lt;/b&gt;: Each next(gen) or loop iteration resumes execution at the last yield, producing the next value.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Exhaustion&lt;/b&gt;: The generator stops when it encounters a return or the end of the function.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3- Simple Problems and Solutions&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem 1: Create a Generator for Even&amp;nbsp;Numbers&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Write a generator function that yields even numbers from 0 to 10. &lt;b&gt;Solution:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;def ev_num(n):
    for i in range(n + 1):  # Loop from 0 to n
        if i % 2 == 0:  # Check if the current number (i) is even
            yield i  # Yield the even number

# Specify n outside the function
n = 10
gen1 = ev_num(n)  # Create generator object

# Iterate through the generator
for a in gen1:
    print(a)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;0
2
4
6
8
10&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem 2: Use a Generator Expression&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Create a generator expression to double numbers from 1 to 5 and print them.&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Solution:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;gen_expr = (x * 2 for x in range(1, 6))
for value in gen_expr:
    print(value)  # Outputs: 2, 4, 6, 8, 10&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4- Challenging Problems for&amp;nbsp;Readers&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, test your skills with these more complex generator problems. Try solving them before checking the solutions below!&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem 3: Infinite Fibonacci Sequence&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Write a generator function that produces an infinite Fibonacci sequence (0, 1, 1, 2, 3, 5, 8,&amp;nbsp;&amp;hellip;). Use it to print the first 10 numbers.&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The infinite Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting with 0 and 1. It continues indefinitely, producing an unending list of numbers. Here are the first few numbers in the sequence to help you understand:&lt;/li&gt;
&lt;li&gt;0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,&amp;nbsp;&amp;hellip;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;- How It&amp;nbsp;Works:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Start with 0 and 1.&lt;/li&gt;
&lt;li&gt;Add the last two numbers to get the next one:&lt;/li&gt;
&lt;li&gt;0 + 1 = 1&lt;/li&gt;
&lt;li&gt;1 + 1 = 2&lt;/li&gt;
&lt;li&gt;1 + 2 = 3&lt;/li&gt;
&lt;li&gt;2 + 3 = 5&lt;/li&gt;
&lt;li&gt;3 + 5 = 8&lt;/li&gt;
&lt;li&gt;And so on&amp;hellip;&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem 4: Filtered Prime Number Generator&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Create a generator function that yields prime numbers up to a given limit (e.g., 20). A prime number is divisible only by 1 and itself.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4- 1 Solutions to Problems&amp;nbsp;3&amp;amp;4&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Solution to Problem 3: Infinite Fibonacci Sequence&lt;/h4&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;def fibonacci_generator():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci_generator()
for _ in range(10):
    print(next(fib))  # Outputs: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Explanation&lt;/b&gt;: The generator uses an infinite loop with yield to produce Fibonacci numbers, updating a and b on each iteration.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Solution to Problem 4: Filtered Prime Number Generator&lt;/h4&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;def prime_generator(limit):
    def is_prime(n):
        if n &amp;lt; 2:
            return False
        for i in range(2, int(n ** 0.5) + 1):
            if n % i == 0:
                return False
        return True
    
    for num in range(limit + 1):
        if is_prime(num):
            yield num

primes = prime_generator(20)
for prime in primes:
    print(prime)  # Outputs: 2, 3, 5, 7, 11, 13, 17, 19&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Explanation&lt;/b&gt;: The is_prime helper function checks for primality, and the generator yields numbers up to the limit that pass this test.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;- Algorithm Summary&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a high-level summary of the algorithm used in the code:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Input:&lt;/b&gt; A number limit that specifies the upper bound for generating prime numbers.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Process:&lt;/b&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;For each number num from 0 to limit:&lt;/li&gt;
&lt;li&gt;Check if num is prime using the is_prime(n) function.&lt;/li&gt;
&lt;li&gt;If num is prime, yield it (make it available to the caller).&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Primality Test (is_prime(n)):&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;If n &amp;lt; 2, it&amp;rsquo;s not prime.&lt;/li&gt;
&lt;li&gt;Check if n is divisible by any integer i from 2 to the square root of n.&lt;/li&gt;
&lt;li&gt;If n is divisible by any i, it&amp;rsquo;s not prime.&lt;/li&gt;
&lt;li&gt;If no divisors are found, n is prime.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. Output:&lt;/b&gt; A sequence of prime numbers, yielded one at a time, which can be consumed by the caller (e.g., printed, stored, or processed further).&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;- Example Walkthrough for limit =&amp;nbsp;10&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To solidify understanding, let&amp;rsquo;s walk through what happens when limit = 10:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;num = 0: is_prime(0) returns False (not prime, no yield).&lt;/li&gt;
&lt;li&gt;num = 1: is_prime(1) returns False (not prime, no yield).&lt;/li&gt;
&lt;li&gt;num = 2: is_prime(2) returns True (prime, yield 2).&lt;/li&gt;
&lt;li&gt;num = 3: is_prime(3) returns True (prime, yield 3).&lt;/li&gt;
&lt;li&gt;num = 4: is_prime(4) checks divisors 2 (4 % 2 = 0), returns False (not prime, no yield).&lt;/li&gt;
&lt;li&gt;num = 5: is_prime(5) checks divisors 2 (5 % 2 = 1), returns True (prime, yield 5).&lt;/li&gt;
&lt;li&gt;num = 6: is_prime(6) checks divisors 2 (6 % 2 = 0), returns False (not prime, no yield).&lt;/li&gt;
&lt;li&gt;num = 7: is_prime(7) checks divisors 2 (7 % 2 = 1), returns True (prime, yield 7).&lt;/li&gt;
&lt;li&gt;num = 8: is_prime(8) checks divisors 2 (8 % 2 = 0), returns False (not prime, no yield).&lt;/li&gt;
&lt;li&gt;num = 9: is_prime(9) checks divisors 2 (9 % 2 = 1), 3 (9 % 3 = 0), returns False (not prime, no yield).&lt;/li&gt;
&lt;li&gt;num = 10: is_prime(10) checks divisors 2 (10 % 2 = 0), returns False (not prime, no yield).&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;5- Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Generators are a powerful feature in Python that enable you to work with sequences in a memory-efficient and elegant way. By mastering generators, you can write cleaner and more efficient code, especially when dealing with large datasets or infinite sequences. Try solving the advanced problems above to deepen your understanding!&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>Fibonacci Sequence</category>
      <category>yield</category>
      <category>이터레이터</category>
      <category>제너레이터</category>
      <category>코딩 강의</category>
      <category>파이썬</category>
      <category>피보나치 수열</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/48</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate008-Understanding-Generators-in-Python#entry48comment</comments>
      <pubDate>Mon, 10 Mar 2025 20:36:12 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_007: Understanding @property and Setter Decorators in&amp;nbsp;Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate007-Understanding-property-and-Setter-Decorators-in-Python</link>
      <description>&lt;p data-ke-size=&quot;size16&quot;&gt;In our last lesson (&lt;a href=&quot;https://codeaddict.tistory.com/entry/Python-Intermediate006-Decorators-in-Python&quot; target=&quot;_blank&quot; rel=&quot;noopener&amp;nbsp;noreferrer&quot;&gt;https://codeaddict.tistory.com/entry/Python-Intermediate006-Decorators-in-Python&lt;/a&gt;), we explored basic and practical decorators like access control. Today, we&amp;rsquo;ll dive into Python&amp;rsquo;s @property decorator and its companion @&amp;lt;property_name&amp;gt;.setter, which transform methods into manageable attributes. These tools are key for encapsulation in object-oriented programming. We&amp;rsquo;ll cover syntax, execution order, and some examples!&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;What Are @property and Setter Decorators?&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;@property&lt;/b&gt;: Converts a method into a getter, letting you access it like an attribute (e.g., obj.name instead of obj.name()).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;@&amp;lt;property_name&amp;gt;.setter&lt;/b&gt;: Defines a method to set the attribute&amp;rsquo;s value, often with validation or logic.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;These are built-in Python decorators for controlling class attribute access, replacing the need for explicit getter/setter methods.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Syntax and Execution Order&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Syntax&lt;/h3&gt;
&lt;pre class=&quot;ruby&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;class MyClass:
    def __init__(self):
        self._value = 0  # Private-ish attribute (convention with underscore)

    @property
    def value(self):  # Getter
        return self._value

    @value.setter
    def value(self, new_value):  # Setter
        self._value = new_value&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Getter&lt;/b&gt;: @property decorates a method to act as an attribute.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Setter&lt;/b&gt;: @value.setter (note the dot notation) decorates a method to handle assignment.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Execution Order&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s how it works when using these decorators:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Class Definition&lt;/b&gt;: Python registers the @property and @&amp;lt;property_name&amp;gt;.setter methods during class creation.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Object Creation&lt;/b&gt;: The __init__ method initializes the underlying attribute (e.g., _value).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Getter Call&lt;/b&gt;: Accessing obj.value invokes the @property-decorated method.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Setter Call&lt;/b&gt;: Assigning obj.value = x invokes the @value.setter-decorated method.&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Example Flow&lt;/h4&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;obj = MyClass()
print(obj.value)  # Step 3: Calls the getter
obj.value = 42    # Step 4: Calls the setter
print(obj.value)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step-by-Step Explanation&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;obj = MyClass()&lt;/b&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;What Happens&lt;/b&gt;: Creates an instance of MyClass. The __init__ method runs, setting self._value = 0 (the initial value).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Function Run&lt;/b&gt;: __init__&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Printed&lt;/b&gt;: Nothing is printed yet.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. print(obj.value)&lt;/b&gt; (First print)&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;What Happens&lt;/b&gt;: Accesses obj.value, which triggers the @property-decorated value method (the getter). This method returns self._value, which is currently 0.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Function Run&lt;/b&gt;: The getter method value(self) under @property.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Printed&lt;/b&gt;: The value returned by the getter, which is 0. So, it prints:&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;0&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. obj.value = 42&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;What Happens&lt;/b&gt;: Assigns 42 to obj.value, triggering the @value.setter-decorated value method (the setter). The setter updates self._value to 42.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Function Run&lt;/b&gt;: The setter method value(self, new_value) under @value.setter.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Printed&lt;/b&gt;: Nothing is printed by default (unless the setter has a print statement, which the base example doesn&amp;rsquo;t). The value of self._value is now 42.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. print(obj.value)&lt;/b&gt; (Second print)&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;What Happens&lt;/b&gt;: Accesses obj.value again, calling the @property-decorated getter method. It returns self._value, which is now 42.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Function Run&lt;/b&gt;: The getter method value(self) under @property.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Printed&lt;/b&gt;: The updated value, which is 42. So, it prints:&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;42&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Practical Example: Managing Employee&amp;nbsp;Salary&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Problem Definition&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You&amp;rsquo;re designing a system to manage employee data. Each employee has a salary, but:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The salary must not be negative (validation required).&lt;/li&gt;
&lt;li&gt;You want to access and update it like an attribute (e.g., emp.salary instead of emp.get_salary()).&lt;/li&gt;
&lt;li&gt;Updates should log changes for auditing.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;How would you implement this? Try solving it before scrolling down!&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Solution&lt;/h3&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;class Employee:
    def __init__(self, name, salary):
        self.name = name
        self._salary = salary  # Private-ish attribute

    @property
    def salary(self):
        print(f&quot;   &amp;rarr; Fetching salary for {self.name}&quot;)
        return self._salary

    @salary.setter
    def salary(self, new_salary):
        if new_salary &amp;lt; 0:
            print(&quot;Error: Salary cannot be negative!&quot;)
            return  # Ignore invalid updates
        print(f&quot;1. Updating salary for {self.name} to {new_salary}&quot;)
        self._salary = new_salary

# Test it
print(&quot;START&quot;)
emp = Employee(&quot;Alice&quot;, 50000)
print(f&quot;Initial salary: {emp.salary}&quot;)
emp.salary = 60000  # Update salary
print(f&quot;New salary: {emp.salary}&quot;)
emp.salary = -1000  # Try invalid update
print(f&quot;Final salary: {emp.salary}&quot;)
print(&quot;END&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output&lt;/h4&gt;
&lt;pre class=&quot;subunit&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;START
   &amp;rarr; Fetching salary for Alice
Initial salary: 50000
1. Updating salary for Alice to 60000
   &amp;rarr; Fetching salary for Alice
New salary: 60000
Error: Salary cannot be negative!
   &amp;rarr; Fetching salary for Alice
Final salary: 60000
END&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Detailed Explanation&lt;/h4&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Class Setup&lt;/b&gt;: Employee uses _salary as a pseudo-private attribute (underscore convention).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;@property&lt;/b&gt;: The salary method becomes a getter. Accessing emp.salary runs this method, logging the fetch and returning _salary.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;@salary.setter&lt;/b&gt;: The setter validates new_salary. If negative, it rejects the change; otherwise, it updates _salary and logs it.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Execution&lt;/b&gt;:&lt;/li&gt;
&lt;/ul&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;emp.salary (getter) fetches the initial value (50000).&lt;/li&gt;
&lt;li&gt;emp.salary = 60000 (setter) updates it with validation.&lt;/li&gt;
&lt;li&gt;emp.salary = -1000 (setter) fails due to the check, keeping the value at 60000.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This encapsulates _salary, enforces rules, and provides a clean interface.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Summary&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;@property&lt;/b&gt;: Turns methods into readable attributes.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;@&amp;lt;property_name&amp;gt;.setter&lt;/b&gt;: Adds logic to attribute assignment (e.g., validation).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Practical Use&lt;/b&gt;: Ideal for managing data like salaries or settings with control.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>object-oriented programming</category>
      <category>property decorator</category>
      <category>setter decorator</category>
      <category>객체 지향 프로그래밍</category>
      <category>데코레이터</category>
      <category>세터 데코레이터</category>
      <category>프로퍼티 데코레이터</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/47</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate007-Understanding-property-and-Setter-Decorators-in-Python#entry47comment</comments>
      <pubDate>Sun, 9 Mar 2025 18:09:04 +0900</pubDate>
    </item>
    <item>
      <title>cpp_014: Passing Arrays and Vectors to Functions in C++ - Syntax and&amp;nbsp;Examples</title>
      <link>https://codeaddict.tistory.com/entry/cpp014-Passing-Arrays-and-Vectors-to-Functions-in-C-Syntax-and-Examples</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Introduction&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In the previous lesson, we explored the differences between arrays and vectors in C++. Now, let&amp;rsquo;s dive deeper into how to pass arrays and vectors to functions in C++. Passing these data structures to functions is a common task in C++ programming, and understanding the syntax and usage is crucial for writing efficient and modular code.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this lesson, we&amp;rsquo;ll cover:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;The syntax for passing arrays and vectors to functions.&lt;/li&gt;
&lt;li&gt;Example problems and solutions.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Passing Arrays to Functions&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Syntax for Passing&amp;nbsp;Arrays&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;When passing an array to a function, you pass a pointer to the first element of the array. The size of the array is often passed as a separate argument.&lt;/p&gt;
&lt;pre class=&quot;reasonml&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;void functionName(T arr[], int size);&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;T is the data type of the array.&lt;/li&gt;
&lt;li&gt;arr[] is the array passed to the function.&lt;/li&gt;
&lt;li&gt;size is the number of elements in the array.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Example 1: Finding the Maximum Element in an&amp;nbsp;Array&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem Statement&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Write a program that takes an array of integers as input, passes it to a function, and finds the maximum element in the array.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Solution&lt;/h4&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;csharp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;
// Function to find the maximum element in an array
int findMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i &amp;lt; size; i++) {
        if (arr[i] &amp;gt; max) {
            max = arr[i];
        }
    }
    return max;
}
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    // Pass the array to the function
    int maxElement = findMax(arr, size);
    cout &amp;lt;&amp;lt; &quot;The maximum element in the array is: &quot; &amp;lt;&amp;lt; maxElement &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output&lt;/h4&gt;
&lt;pre class=&quot;smali&quot; data-code-block-lang=&quot;csharp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;The maximum element in the array is: 50&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Passing Vectors to Functions&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Syntax for Passing&amp;nbsp;Vectors&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Vectors are passed to functions by reference or by value. Passing by reference is more efficient for large vectors.&lt;/p&gt;
&lt;pre class=&quot;reasonml&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;void functionName(vector&amp;lt;T&amp;gt; &amp;amp;vec);&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;T is the data type of the vector.&lt;/li&gt;
&lt;li&gt;&amp;amp;vec is the vector passed by reference, meaning that any modifications in the function will directly affect the original vector.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Note:&lt;/b&gt;&lt;br /&gt;For a deeper understanding of how &lt;b&gt;references&lt;/b&gt; work (indicated by &amp;amp;), please refer to the additional example at the end of this tutorial.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Example 2: Calculating the Sum of Elements in a&amp;nbsp;Vector&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem Statement&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Write a program that takes a vector of integers as input, passes it to a function, and calculates the sum of its elements.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Solution&lt;/h4&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;
// Function to calculate the sum of elements in a vector
int calculateSum(vector&amp;lt;int&amp;gt; &amp;amp;vec) {
    int sum = 0;
    for (int i = 0; i &amp;lt; vec.size(); i++) {
        sum += vec[i];
    }
    return sum;
}
int main() {
    vector&amp;lt;int&amp;gt; vec = {1, 2, 3, 4, 5};
    // Pass the vector to the function
    int sum = calculateSum(vec);
    cout &amp;lt;&amp;lt; &quot;The sum of elements in the vector is: &quot; &amp;lt;&amp;lt; sum &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output&lt;/h4&gt;
&lt;pre class=&quot;maxima&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;The sum of elements in the vector is: 15&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Note about &lt;/b&gt;&lt;b&gt;size()&lt;/b&gt;&lt;b&gt;:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The size() function is a member of the vector class, and it returns the number of elements in the vector.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Important:&lt;/b&gt; Since vectors are dynamic, they don&amp;rsquo;t require manual size calculations like arrays. You can simply use vec.size() to get the number of elements.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Comparing Array and Vector&amp;nbsp;Usage&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Example 3: Modifying Elements in an Array and&amp;nbsp;Vector&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem Statement&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Write a program that demonstrates how to modify elements in an array and a vector by passing them to functions.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Solution&lt;/h4&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

// Function to modify an array
void modifyArray(int arr[], int size) {
    for (int i = 0; i &amp;lt; size; i++) {
        arr[i] *= 2; // Double each element
    }
}
// Function to modify a vector
void modifyVector(vector&amp;lt;int&amp;gt; &amp;amp;vec) {
    for (int i = 0; i &amp;lt; vec.size(); i++) {
        vec[i] *= 2; // Double each element
    }
}
int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    vector&amp;lt;int&amp;gt; vec = {1, 2, 3, 4, 5};
    // Pass the array and vector to functions
    modifyArray(arr, size);
    modifyVector(vec);
    cout &amp;lt;&amp;lt; &quot;Modified array: &quot;;
    for (int i = 0; i &amp;lt; size; i++) {
        cout &amp;lt;&amp;lt; arr[i] &amp;lt;&amp;lt; &quot; &quot;;
    }
    cout &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Modified vector: &quot;;
    for (int i = 0; i &amp;lt; vec.size(); i++) {
        cout &amp;lt;&amp;lt; vec[i] &amp;lt;&amp;lt; &quot; &quot;;
    }
    cout &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output&lt;/h4&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Modified array: 2 4 6 8 10  
Modified vector: 2 4 6 8 10&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;_________________________________________________________________&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Additional Note on &amp;amp; (Reference) in Vectors and&amp;nbsp;Arrays&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In C++, when we pass a vector or array to a function using &amp;amp;, we are &lt;b&gt;passing it by reference&lt;/b&gt;. This means that the function works directly with the original vector or array, not a copy. Any changes made to the vector or array inside the function will directly affect the original vector or array outside the function. This is more &lt;b&gt;efficient&lt;/b&gt; for large vectors because it avoids the overhead of copying the entire data structure.&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Example of Passing by Reference&lt;/b&gt;:&lt;br /&gt;&amp;nbsp;void modifyVector(vector&amp;lt;int&amp;gt; &amp;amp;vec)&lt;br /&gt;&amp;nbsp;The &amp;amp; symbol indicates that the vector is being passed by reference. This allows the function to directly modify the contents of the vector.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Understanding References with &amp;amp; (simple example for beginners)&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To understand the concept of &lt;b&gt;passing by reference&lt;/b&gt; using &amp;amp;, consider this simple example:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

void modifyValue(int &amp;amp;x) {  // Passed by reference
    x = 20;  // Modify the original value
}
int main() {
    int num = 10;
    modifyValue(num);  // Pass 'num' by reference
    cout &amp;lt;&amp;lt; &quot;Modified value: &quot; &amp;lt;&amp;lt; num &amp;lt;&amp;lt; endl;  // Output will be 20
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;avrasm&quot;&gt;&lt;code&gt;Output:&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Modified value: 20&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;In this example, modifyValue takes an integer parameter x passed by reference. This means that when x is modified inside the function, the original num variable is also modified.&lt;/li&gt;
&lt;li&gt;So, the value of num changes to 20 inside the function, and the modified value is reflected when we print it in main().&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Example 2: Passing by Value (without&amp;nbsp;&amp;amp;)&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

void modifyValue(int x) {  // Passed by value
    x = 20;  // Modify the local copy of the value
}

int main() {
    int num = 10;
    modifyValue(num);  // Pass 'num' by value
    cout &amp;lt;&amp;lt; &quot;Modified value: &quot; &amp;lt;&amp;lt; num &amp;lt;&amp;lt; endl;  // Output will be 10
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Modified value: 10&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;In this case, modifyValue takes an integer parameter x passed &lt;b&gt;by value&lt;/b&gt;. This means that a &lt;b&gt;copy&lt;/b&gt; of num is passed to the function, and any changes made to x inside the function do not affect the original num in main().&lt;/li&gt;
&lt;li&gt;So, even though we modify x inside the function, the value of num remains unchanged and is still 10 when printed.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Summary:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Passing by Reference (&lt;/b&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;b&gt;)&lt;/b&gt; allows the function to modify the original variable, so changes are reflected outside the function.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Passing by Value&lt;/b&gt; creates a copy of the variable, so modifications inside the function do not affect the original variable.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;_________________________________________________________________&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>c++  벡터</category>
      <category>c++ array vs vector</category>
      <category>c++ arrays and vectors</category>
      <category>c++ programming basics</category>
      <category>C++ 배열</category>
      <category>c++ 배열 vs 벡터</category>
      <category>c++ 예제 문제</category>
      <category>c++ 함수 사용법</category>
      <category>passing arrays to functions</category>
      <category>함수</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/46</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp014-Passing-Arrays-and-Vectors-to-Functions-in-C-Syntax-and-Examples#entry46comment</comments>
      <pubDate>Sun, 9 Mar 2025 17:41:28 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_006: Decorators in&amp;nbsp;Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate006-Decorators-in-Python</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Decorators in Python are a powerful feature that allows you to modify or extend the behavior of functions without changing their actual code. In this blog post, we&amp;rsquo;ll explore two examples: a basic decorator to add behavior around a function and a more practical one to simulate access control. Let&amp;rsquo;s get started!&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. Basic Decorator Example&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a simple decorator that adds some behavior before and after a function call:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class=&quot;pgsql&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;def my_decorator(func):
    def wrapper(*args, **kwargs):
        print(&quot;1. Before function call&quot;)  
        result = func(*args, **kwargs)  
        print(&quot;2. After function call&quot;) 
        return result  
    return wrapper  

@my_decorator
def add(x, y):
    print(&quot;   &amp;rarr; Inside function: Adding numbers&quot;)  # Step 3.1
    return x + y  

print(&quot;START&quot;)  
result = add(3, 4)  
print(f&quot;RESULT: {result}&quot;)  
print(&quot;END&quot;)  &lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output:&lt;/h4&gt;
&lt;pre class=&quot;sql&quot; data-code-block-lang=&quot;sql&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;START
1. Before function call
   &amp;rarr; Inside function: Adding numbers
2. After function call
RESULT: 7
END&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Order of Execution&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s break down the order in which the code is executed:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;635&quot; data-origin-height=&quot;729&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/bftFE3/btsMAEXD6aB/1l3zQCKKwPoQQpMUzmQr91/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/bftFE3/btsMAEXD6aB/1l3zQCKKwPoQQpMUzmQr91/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/bftFE3/btsMAEXD6aB/1l3zQCKKwPoQQpMUzmQr91/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbftFE3%2FbtsMAEXD6aB%2F1l3zQCKKwPoQQpMUzmQr91%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;635&quot; height=&quot;729&quot; data-origin-width=&quot;635&quot; data-origin-height=&quot;729&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Practical Example: Access Control Decorator&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, let&amp;rsquo;s create a more useful decorator that simulates restricting access to a function based on a condition (e.g., user authentication). This is a simplified version of what you might see in web frameworks like Flask.&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;def require_auth(func):
    def wrapper(user, *args, **kwargs):
        # Simulate checking if the user is authenticated
        if user.get(&quot;is_authenticated&quot;, False):  # Check if user is authenticated
            print(&quot;1. Access granted!&quot;)
            return func(user, *args, **kwargs)   # Call the original function
        else:
            print(&quot;1. Access denied: Please log in.&quot;)
            return None                          # Return None if access is denied
    return wrapper

@require_auth
def view_profile(user):
    print(&quot;   &amp;rarr; Inside function: Fetching profile data&quot;)
    return f&quot;Profile: {user['username']}&quot;

# Test with an unauthenticated user
user1 = {&quot;username&quot;: &quot;Alice&quot;, &quot;is_authenticated&quot;: False}
print(&quot;START&quot;)
result = view_profile(user1)
print(f&quot;RESULT: {result}&quot;)
print(&quot;END&quot;)

# Test with an authenticated user
user2 = {&quot;username&quot;: &quot;Bob&quot;, &quot;is_authenticated&quot;: True}
print(&quot;\nSTART&quot;)
result = view_profile(user2)
print(f&quot;RESULT: {result}&quot;)
print(&quot;END&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;sql&quot; data-code-block-lang=&quot;sql&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;START
1. Access denied: Please log in.
RESULT: None
END

START
1. Access granted!
   &amp;rarr; Inside function: Fetching profile data
RESULT: Profile: Bob
END&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Order of Execution (for&amp;nbsp;user2)&lt;/h3&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Step 1: @require_auth &amp;mdash; The view_profile function is wrapped by require_auth.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 2: print(&amp;ldquo;START&amp;rdquo;) &amp;mdash; Prints &amp;ldquo;START&amp;rdquo; before calling the function.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 3: result = view_profile(user2) &amp;rarr; calls wrapper &amp;mdash; The decorator runs before view_profile().&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 4: if user.get(&amp;ldquo;is_authenticated&amp;rdquo;, False) &amp;mdash; Checks if the user is authenticated (True for user2).&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 5: print(&amp;ldquo;1. Access granted!&amp;rdquo;) &amp;mdash; Prints &amp;ldquo;Access granted!&amp;rdquo; since the condition is met.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 6: func(user, *args, **kwargs) &amp;rarr; Calls view_profile &amp;mdash; The original function view_profile is called with user2.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 7: print(&amp;ldquo; &amp;rarr; Inside function: Fetching profile data&amp;rdquo;) &amp;mdash; Prints inside view_profile().&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 8: return f&amp;rdquo;Profile: {user[&amp;lsquo;username&amp;rsquo;]}&amp;rdquo; &amp;mdash; Returns &amp;ldquo;Profile: Bob&amp;rdquo; to wrapper.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 9: return func(&amp;hellip;) &amp;mdash; wrapper returns the result to result.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 10: print(f&amp;rdquo;RESULT: {result}&amp;rdquo;) &amp;mdash; Prints &amp;ldquo;RESULT: Profile: Bob&amp;rdquo;.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;Step 11: print(&amp;ldquo;END&amp;rdquo;) &amp;mdash; Prints &amp;ldquo;END&amp;rdquo;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;For user1: The decorator stops at step 4, prints &amp;ldquo;Access denied: Please log in.&amp;rdquo;, and returns None.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Decorators are incredibly versatile! The access control example shows how they&amp;rsquo;re used in frameworks to manage permissions. Try tweaking the require_auth decorator to log failed attempts or add more conditions!  &lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>decorators</category>
      <category>Python</category>
      <category>데코레이터</category>
      <category>파이썬</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/45</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate006-Decorators-in-Python#entry45comment</comments>
      <pubDate>Tue, 4 Mar 2025 22:34:04 +0900</pubDate>
    </item>
    <item>
      <title>DjangoAPI_001_Docker Setup with GitHub and Docker&amp;nbsp;Hub</title>
      <link>https://codeaddict.tistory.com/entry/DjangoAPI001Docker-Setup-with-GitHub-and-Docker-Hub</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Overview and Summary of&amp;nbsp;Steps&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This tutorial guides you through setting up a Django project for a REST API using Docker and Docker Compose, linking it to GitHub for version control, and pushing it to Docker Hub securely &amp;mdash; all without needing Python&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Summary of Steps:&lt;/b&gt;&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Start a Project on GitHub&lt;/b&gt;: Create and clone a repository.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Add Docker Hub Secrets in GitHub&lt;/b&gt;: Store Docker Hub credentials securely.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Set Up the Project Locally&lt;/b&gt;: Add Docker files and create a Django app in a container.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Run the Server&lt;/b&gt;: Launch the app with Docker Compose.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Push to Docker Hub&lt;/b&gt;: Share your Docker image online.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s get started!&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 1: Start a Project on GitHub for Our&amp;nbsp;Apps&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;1.1 Create a GitHub Repository&lt;/h4&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;&amp;nbsp;&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Go to &lt;a href=&quot;https://github.com&quot; data-href=&quot;https://github.com&quot;&gt;GitHub&lt;/a&gt; and log in.&lt;/li&gt;
&lt;li&gt;Click &lt;b&gt;+ New Repository&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Name it (e.g., my-django-project).&lt;/li&gt;
&lt;li&gt;Check &lt;b&gt;Add a README file&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Select &lt;b&gt;Python&lt;/b&gt; under &lt;b&gt;Add&amp;nbsp;.gitignore&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Click &lt;b&gt;Create Repository&lt;/b&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;1.2 Clone It&amp;nbsp;Locally&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Copy the SSH URL (e.g., git@github.com:your-username/my-django-project.git).&lt;/li&gt;
&lt;li&gt;Open your terminal.&lt;/li&gt;
&lt;li&gt;Navigate to your folder:&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;cd /path/to/your/folder&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;4. Clone it:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;git clone git@github.com:your-username/my-django-project.git&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;5. Enter the folder:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;cd my-django-project&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 2: Set Up Docker Hub Authentication&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To push Docker images, we need &lt;b&gt;authentication&lt;/b&gt;. Instead of using passwords (which are insecure), we use &lt;b&gt;Access Tokens&lt;/b&gt;.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2.1 What is a Credential?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A &lt;b&gt;credential&lt;/b&gt; is proof of identity (like a username and password or an API token).&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Docker Hub requires authentication&lt;/b&gt; to push/pull images.&lt;/li&gt;
&lt;li&gt;Instead of a password, we use an &lt;b&gt;Access Token&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;This is safer, as we can &lt;b&gt;revoke&lt;/b&gt; the token if needed.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2.2 Generate a Docker Hub Access&amp;nbsp;Token&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Go to Docker Hub.&lt;/li&gt;
&lt;li&gt;Log in to your account.&lt;/li&gt;
&lt;li&gt;Go to your Docker Hub account settings (top-right corner &amp;gt; &amp;ldquo;Account Settings&amp;rdquo;).&lt;/li&gt;
&lt;li&gt;Navigate to &amp;ldquo;Personal access tokens&amp;rdquo; and click &amp;ldquo;Generate new token.&amp;rdquo;&lt;/li&gt;
&lt;li&gt;Give it a name (e.g., my-django-project), set permissions (e.g., &amp;ldquo;Read &amp;amp; Write&amp;rdquo;), Click &lt;b&gt;Generate &lt;/b&gt;and copy the token.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Copy the token immediately&lt;/b&gt; (you will not see it again).&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;  Why do we need an Access Token?&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Security:&lt;/b&gt; Safer than passwords.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Automation:&lt;/b&gt; Allows scripts and CI/CD pipelines to authenticate.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Revocability:&lt;/b&gt; You can delete a token without affecting your account.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 3: Store Docker Credentials in GitHub&amp;nbsp;Secrets&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, we will store our credentials in &lt;b&gt;GitHub Secrets&lt;/b&gt; for secure access in CI/CD pipelines.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3.1 Add Docker Hub Credentials to&amp;nbsp;GitHub&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Go to your &lt;b&gt;GitHub repository&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Click &lt;b&gt;Settings&lt;/b&gt; &amp;rarr; &lt;b&gt;Secrets and variables&lt;/b&gt; &amp;rarr; &lt;b&gt;Actions&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Click &lt;b&gt;New repository secret&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Add the first secret:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Name:&lt;/b&gt; DOCKERHUB_USERNAME&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Value:&lt;/b&gt; (Your Docker Hub username)&lt;/li&gt;
&lt;li&gt;Click &lt;b&gt;Add Secret&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;5. Add the second secret:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Name:&lt;/b&gt; DOCKERHUB_TOKEN&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Value:&lt;/b&gt; (Paste the Docker Hub Access Token you copied earlier)&lt;/li&gt;
&lt;li&gt;Click &lt;b&gt;Add Secret&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 4: Make a Project on Our Machine by Adding Dockerfile, Docker Compose File, Requirements File, and Creating a Blank Django App Using Django&amp;nbsp;CLI&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;4.1 Ensure Docker is&amp;nbsp;Running&lt;/h4&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Install &lt;a href=&quot;https://www.docker.com/products/docker-desktop/&quot; data-href=&quot;https://www.docker.com/products/docker-desktop/&quot;&gt;Docker Desktop&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Start Docker Desktop.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;4.2 Create a requirements.txt File&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;In my-django-project, create requirements.txt and save it.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;django==4.2&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Why?&lt;/b&gt; Lists packages for Docker to install.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;4.3 Create a Dockerfile&amp;nbsp;&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Create Dockerfile in my-django-project.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;vala&quot; data-code-block-lang=&quot;shell&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;FROM python:3.9
# Starts with Python 3.9 from Docker Hub.
# Options: python:3.10, python:3.9-slim, python:3.9-alpine

WORKDIR /app
# Sets &quot;/app&quot; as the working folder.
# Options: WORKDIR /myproject, omit it

COPY requirements.txt .
# Copies requirements.txt to /app.
# Options: COPY ./requirements.txt /app/req.txt

RUN pip install --no-cache-dir -r requirements.txt
# Installs Django, keeps image small.
# Options: RUN pip install -r requirements.txt

COPY . .
# Copies all project files to /app.
# Options: COPY ./app /app

EXPOSE 8000
# Opens port 8000.
# Options: EXPOSE 5000&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Why?&lt;/b&gt; Builds the container for your app.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;4.4 Create a docker-compose.yml File with Detailed Explanations&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Create docker-compose.yml in my-django-project.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;version: '3.8'
# Sets Compose version.
# Options: '3.9', '2'

services:
  app:
    # Service name.
    # Options: web, django

    build: .
    # Builds from Dockerfile.
    # Options: build: ./docker, image: my-django-app

    ports:
      - &quot;8000:8000&quot;
    # Maps port 8000.
    # Options: &quot;5000:5000&quot;, &quot;8080:8000&quot;

    volumes:
      - .:/app
    # Syncs local folder with /app.
    # Options: ./code:/app, omit it

    command: python manage.py runserver 0.0.0.0:8000
    # Runs Django server.
    # Options: command: bash&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Why?&lt;/b&gt; Manages your app&amp;rsquo;s container.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;4.5 Create a&amp;nbsp;.dockerignore File&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Create&amp;nbsp;.dockerignore in my-django-project.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;markdown&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;__pycache__
*.pyc
.git
.gitignore&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Why?&lt;/b&gt; Keeps container clean.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 5: Create a New Django Project Inside the Container&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Build the Docker Image&lt;/b&gt;&lt;br /&gt;Run the following command to build the Docker image:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;ebnf&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;docker-compose build&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Create a New Django Project&lt;/b&gt;&lt;br /&gt;Use docker-compose run to create a new Django project inside the container:&lt;/p&gt;
&lt;pre class=&quot;stata&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;docker-compose run - rm app sh -c &quot;django-admin startproject app .&quot;&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;This creates a new Django project named app in the /app directory inside the container, which is synced with your local project folder.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Verify the Project Structure&lt;/b&gt;&lt;br /&gt;After running the command, you should see the following files in your local project folder:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;my-django-app/&lt;br /&gt;├── app/&lt;br /&gt;│ ├── __init__.py&lt;br /&gt;│ ├── asgi.py&lt;br /&gt;│ ├── settings.py&lt;br /&gt;│ ├── urls.py&lt;br /&gt;│ └── wsgi.py&lt;br /&gt;├── manage.py&lt;br /&gt;├── requirements.txt&lt;br /&gt;├── Dockerfile&lt;br /&gt;├── docker-compose.yml&lt;br /&gt;└──&amp;nbsp;.dockerignore&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 6: Run the Django Development Server&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Start the Container&lt;/b&gt;&lt;br /&gt;Run the following command to start the container:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;ebnf&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;docker-compose up&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Access Your Django App&lt;/b&gt;&lt;br /&gt;Open your browser and go to http://localhost:8000. You should see the Django welcome page.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Backend REST API with Python &amp;amp; Django</category>
      <category>devops</category>
      <category>django</category>
      <category>docker</category>
      <category>REST API</category>
      <category>restapi</category>
      <category>도커</category>
      <category>도커 허브</category>
      <category>백엔드 개발</category>
      <category>장고</category>
      <category>컨테이너화</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/44</guid>
      <comments>https://codeaddict.tistory.com/entry/DjangoAPI001Docker-Setup-with-GitHub-and-Docker-Hub#entry44comment</comments>
      <pubDate>Sun, 2 Mar 2025 18:32:45 +0900</pubDate>
    </item>
    <item>
      <title>cpp_014: Exploring Different Types of For Loops in C++ &amp;mdash; Range-Based and Reference-Based Loops</title>
      <link>https://codeaddict.tistory.com/entry/cpp014-Exploring-Different-Types-of-For-Loops-in-C-%E2%80%94-Range-Based-and-Reference-Based-Loops</link>
      <description>&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;4533&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;Introduction&lt;/h1&gt;
&lt;p id=&quot;da34&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In one of the previous lessons (&lt;b&gt;cpp_008: for Loops in C++)&lt;/b&gt;, we covered the basics of&lt;span&gt;&amp;nbsp;&lt;/span&gt;for&lt;span&gt;&amp;nbsp;&lt;/span&gt;loops, including their syntax and common use cases.&lt;/p&gt;
&lt;div&gt;&lt;a style=&quot;color: #000000;&quot; href=&quot;https://medium.com/@staytechrich/cpp-008-for-loops-in-c-96c966c340cd?source=post_page-----8060abf5b642---------------------------------------&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p style=&quot;color: #6b6b6b;&quot; data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/a&gt;&lt;/div&gt;
&lt;p id=&quot;9a3d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;In this lesson, we&amp;rsquo;ll explore&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;different types of&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;/b&gt;&lt;b&gt;for&lt;/b&gt;&lt;b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;loops&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;in C++, specifically focusing on&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;range-based for loops&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;and&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;reference-based for loops&lt;/b&gt;. These loops provide cleaner, more efficient, and safer ways to iterate over collections like arrays, vectors, and other containers. We&amp;rsquo;ll explain why and when to use these loops, along with examples and outputs to help beginners understand these concepts easily.&lt;/p&gt;
&lt;p id=&quot;da16&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;If you&amp;rsquo;re not familiar with&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;vectors&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;in C++, I recommend checking out our previous lessons on&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;arrays and vectors&lt;/b&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;before diving into this post.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;9b5d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Range-Based For Loops&lt;/h1&gt;
&lt;h1 id=&quot;fe16&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  General Rule and Syntax&lt;/h1&gt;
&lt;p id=&quot;edde&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Range-based&lt;span&gt;&amp;nbsp;&lt;/span&gt;for&lt;span&gt;&amp;nbsp;&lt;/span&gt;loops, simplify iterating over collections like arrays, vectors, and other containers. The syntax is:&lt;/p&gt;
&lt;pre class=&quot;smali&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;for (type variable : collection) {
    // Code block to execute
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;f619&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here,&lt;span&gt;&amp;nbsp;&lt;/span&gt;type&lt;span&gt;&amp;nbsp;&lt;/span&gt;is the data type of the elements in the collection,&lt;span&gt;&amp;nbsp;&lt;/span&gt;variable&lt;span&gt;&amp;nbsp;&lt;/span&gt;is the loop variable, and&lt;span&gt;&amp;nbsp;&lt;/span&gt;collection&lt;span&gt;&amp;nbsp;&lt;/span&gt;is the container (e.g., array, vector).&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;d160&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Explanation of the Syntax&lt;/h1&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;4eb0&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Automatic Iteration&lt;/b&gt;:&lt;br /&gt;The loop automatically iterates over each element in the collection, eliminating the need for manual indexing.&lt;/li&gt;
&lt;li id=&quot;59ba&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Read-Only by Default&lt;/b&gt;:&lt;br /&gt;By default, the loop variable (variable) is a copy of the element in the collection. This means modifications to&lt;span&gt;&amp;nbsp;&lt;/span&gt;variable&lt;span&gt;&amp;nbsp;&lt;/span&gt;do not affect the original collection.&lt;/li&gt;
&lt;li id=&quot;3f55&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Cleaner Code&lt;/b&gt;:&lt;br /&gt;Range-based loops reduce boilerplate code, making it easier to read and maintain.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;abb0&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Example 1: Range-Based Loop with Vectors&lt;/h1&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    vector&amp;lt;int&amp;gt; vec = {1, 2, 3, 4, 5};
    cout &amp;lt;&amp;lt; &quot;Vector elements: &quot;;
    for (int num : vec) {
        cout &amp;lt;&amp;lt; num &amp;lt;&amp;lt; &quot; &quot;;
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;b398&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Vector elements: 1 2 3 4 5&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;f524&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;7b20&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The loop iterates over each element in the vector&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.&lt;/li&gt;
&lt;li id=&quot;7a22&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The variable&lt;span&gt;&amp;nbsp;&lt;/span&gt;num&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a copy of the current element, so changes to&lt;span&gt;&amp;nbsp;&lt;/span&gt;num&lt;span&gt;&amp;nbsp;&lt;/span&gt;do not affect&lt;span&gt;&amp;nbsp;&lt;/span&gt;vec.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;f39b&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Reference-Based For Loops&lt;/h1&gt;
&lt;h1 id=&quot;af8e&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  General Rule and Syntax&lt;/h1&gt;
&lt;p id=&quot;d322&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;When you want to modify the elements of a collection during iteration, you can use a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;reference-based for loop&lt;/b&gt;. The syntax is:&lt;/p&gt;
&lt;pre class=&quot;smali&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;for (type&amp;amp; variable : collection) {
    // Code block to execute
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;458a&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here,&lt;span&gt;&amp;nbsp;&lt;/span&gt;type&amp;amp;&lt;span&gt;&amp;nbsp;&lt;/span&gt;indicates that&lt;span&gt;&amp;nbsp;&lt;/span&gt;variable&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a reference to the elements in the collection.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;426c&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Explanation of the Syntax&lt;/h1&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;fe8c&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Reference Mechanism&lt;/b&gt;:&lt;br /&gt;The loop variable (variable) is a reference to the actual element in the collection, not a copy.&lt;/li&gt;
&lt;li id=&quot;049e&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Modifications Affect the Original Collection&lt;/b&gt;:&lt;br /&gt;Changes made to&lt;span&gt;&amp;nbsp;&lt;/span&gt;variable&lt;span&gt;&amp;nbsp;&lt;/span&gt;inside the loop will modify the original collection.&lt;/li&gt;
&lt;li id=&quot;907f&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Efficiency&lt;/b&gt;:&lt;br /&gt;Using references avoids copying elements, which is especially beneficial for large collections or complex objects.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;e6b9&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Example 2: Reference-Based Loop with Vectors&lt;/h1&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    vector&amp;lt;int&amp;gt; vec = {1, 2, 3, 4, 5};
    cout &amp;lt;&amp;lt; &quot;Original vector: &quot;;
    for (int num : vec) {
        cout &amp;lt;&amp;lt; num &amp;lt;&amp;lt; &quot; &quot;;
    }
    cout &amp;lt;&amp;lt; endl;
    // Modify the vector using a reference-based loop
    for (int&amp;amp; num : vec) {
        num *= 2; // Double each element
    }
    cout &amp;lt;&amp;lt; &quot;Modified vector: &quot;;
    for (int num : vec) {
        cout &amp;lt;&amp;lt; num &amp;lt;&amp;lt; &quot; &quot;;
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;2e9d&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Original vector: 1 2 3 4 5  
Modified vector: 2 4 6 8 10&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;df6b&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;8650&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The first loop prints the original vector.&lt;/li&gt;
&lt;li id=&quot;dc21&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The second loop uses a reference (int&amp;amp; num) to double each element in the vector.&lt;/li&gt;
&lt;li id=&quot;0f80&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The changes are reflected in the original vector.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;2b89&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Const Reference-Based For Loops&lt;/h1&gt;
&lt;h1 id=&quot;8733&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  General Rule and Syntax&lt;/h1&gt;
&lt;p id=&quot;2c7b&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;When you want to iterate over a collection without modifying its elements, you can use a&lt;span&gt;&amp;nbsp;&lt;/span&gt;&lt;b&gt;const reference-based for loop&lt;/b&gt;. The syntax is:&lt;/p&gt;
&lt;pre class=&quot;smali&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;for (const type&amp;amp; variable : collection) {
    // Code block to execute
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;00af&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;Here,&lt;span&gt;&amp;nbsp;&lt;/span&gt;const type&amp;amp;&lt;span&gt;&amp;nbsp;&lt;/span&gt;ensures that&lt;span&gt;&amp;nbsp;&lt;/span&gt;variable&lt;span&gt;&amp;nbsp;&lt;/span&gt;is a read-only reference to the elements in the collection.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;3f64&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Explanation of the Syntax&lt;/h1&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;4477&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Read-Only Access&lt;/b&gt;:&lt;br /&gt;The loop variable (variable) cannot be modified, ensuring the collection remains unchanged.&lt;/li&gt;
&lt;li id=&quot;3d73&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Efficiency&lt;/b&gt;:&lt;br /&gt;Using&lt;span&gt;&amp;nbsp;&lt;/span&gt;const&lt;span&gt;&amp;nbsp;&lt;/span&gt;references avoids copying elements while preventing accidental modifications.&lt;/li&gt;
&lt;li id=&quot;6892&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Safety&lt;/b&gt;:&lt;br /&gt;This approach is ideal for scenarios where you need to ensure data integrity.&lt;/li&gt;
&lt;/ol&gt;
&lt;h1 id=&quot;7491&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Example 3: Const Reference-Based Loop with Vectors&lt;/h1&gt;
&lt;pre class=&quot;cpp&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    vector&amp;lt;int&amp;gt; vec = {1, 2, 3, 4, 5};
    cout &amp;lt;&amp;lt; &quot;Vector elements (read-only): &quot;;
    for (const int&amp;amp; num : vec) {
        cout &amp;lt;&amp;lt; num &amp;lt;&amp;lt; &quot; &quot;;
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;a5a5&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; style=&quot;background-color: #f9f9f9; color: #242424;&quot;&gt;&lt;code&gt;Vector elements (read-only): 1 2 3 4 5&lt;/code&gt;&lt;/pre&gt;
&lt;p id=&quot;3565&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li id=&quot;abff&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The loop iterates over the vector using a&lt;span&gt;&amp;nbsp;&lt;/span&gt;const&lt;span&gt;&amp;nbsp;&lt;/span&gt;reference.&lt;/li&gt;
&lt;li id=&quot;0e69&quot; style=&quot;list-style-type: disc; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;The elements cannot be modified inside the loop, ensuring the vector remains unchanged.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;&amp;nbsp;&lt;/div&gt;
&lt;div style=&quot;background-color: #ffffff; color: #000000; text-align: start;&quot;&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h1 id=&quot;0b4f&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  When to Use Each Type of Loop&lt;/h1&gt;
&lt;div&gt;
&lt;div&gt;&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;875&quot; data-origin-height=&quot;270&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/bGGMrj/btsMx9w6uxq/hdMMbD5rMKrNu91agCVzS1/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/bGGMrj/btsMx9w6uxq/hdMMbD5rMKrNu91agCVzS1/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/bGGMrj/btsMx9w6uxq/hdMMbD5rMKrNu91agCVzS1/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbGGMrj%2FbtsMx9w6uxq%2FhdMMbD5rMKrNu91agCVzS1%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;700&quot; height=&quot;216&quot; data-origin-width=&quot;875&quot; data-origin-height=&quot;270&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;h1 id=&quot;38c2&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;  Key Takeaways&lt;/h1&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li id=&quot;05bd&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Range-Based Loops&lt;/b&gt;: Simplify iteration over collections but work with copies of elements by default.&lt;/li&gt;
&lt;li id=&quot;3675&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Reference-Based Loops&lt;/b&gt;: Allow modification of the original collection and avoid copying elements.&lt;/li&gt;
&lt;li id=&quot;041b&quot; style=&quot;list-style-type: decimal; color: #242424;&quot; data-selectable-paragraph=&quot;&quot;&gt;&lt;b&gt;Const Reference-Based Loops&lt;/b&gt;: Provide efficient, read-only access to collections.&lt;/li&gt;
&lt;/ol&gt;
&lt;p id=&quot;8656&quot; style=&quot;color: #242424;&quot; data-selectable-paragraph=&quot;&quot; data-ke-size=&quot;size16&quot;&gt;By understanding these different types of&lt;span&gt;&amp;nbsp;&lt;/span&gt;for&lt;span&gt;&amp;nbsp;&lt;/span&gt;loops, you can write cleaner, more efficient, and safer C++ code.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>C++ Programming</category>
      <category>C++ 프로그래밍</category>
      <category>c++에서의 const 참조</category>
      <category>const reference in c++</category>
      <category>efficient loops in c++</category>
      <category>iterating over vectors</category>
      <category>range-based for loops</category>
      <category>reference-based for loops</category>
      <category>범위 기반 for 루프</category>
      <category>참조 기반 for 루프</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/43</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp014-Exploring-Different-Types-of-For-Loops-in-C-%E2%80%94-Range-Based-and-Reference-Based-Loops#entry43comment</comments>
      <pubDate>Sat, 1 Mar 2025 22:51:48 +0900</pubDate>
    </item>
    <item>
      <title>cpp_013: Arrays vs. Vectors in C++ - Understanding the Differences with&amp;nbsp;Examples</title>
      <link>https://codeaddict.tistory.com/entry/cpp013-Arrays-vs-Vectors-in-C-Understanding-the-Differences-with-Examples</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Introduction&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In C++, both &lt;b&gt;arrays&lt;/b&gt; and &lt;b&gt;vectors&lt;/b&gt; allow us to store multiple values in a structured format. However, they have fundamental differences in &lt;b&gt;memory management, flexibility, and ease of use&lt;/b&gt;. This lesson will compare &lt;b&gt;C++ arrays and vectors&lt;/b&gt;, highlight their key differences, and provide two example problems demonstrating when to use each.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Comparing the Syntax of Arrays and&amp;nbsp;Vectors&lt;/h3&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;951&quot; data-origin-height=&quot;345&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/bbfIrP/btsMwYBZCOT/Hn4wz3F0JOXRkNnlwEHs7K/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/bbfIrP/btsMwYBZCOT/Hn4wz3F0JOXRkNnlwEHs7K/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/bbfIrP/btsMwYBZCOT/Hn4wz3F0JOXRkNnlwEHs7K/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbbfIrP%2FbtsMwYBZCOT%2FHn4wz3F0JOXRkNnlwEHs7K%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;951&quot; height=&quot;345&quot; data-origin-width=&quot;951&quot; data-origin-height=&quot;345&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;Here, T is the data type (e.g., int, double, char), and N is the number of elements.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Key Differences Between Arrays and&amp;nbsp;Vectors&lt;/h3&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;937&quot; data-origin-height=&quot;305&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/eDOR7k/btsMxDD8FqU/Um9jGDFkRvBylTmKi9FBXk/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/eDOR7k/btsMxDD8FqU/Um9jGDFkRvBylTmKi9FBXk/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/eDOR7k/btsMxDD8FqU/Um9jGDFkRvBylTmKi9FBXk/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FeDOR7k%2FbtsMxDD8FqU%2FUm9jGDFkRvBylTmKi9FBXk%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;937&quot; height=&quot;305&quot; data-origin-width=&quot;937&quot; data-origin-height=&quot;305&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;  Example 1: Finding the Sum of Elements&lt;/b&gt;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;  &lt;b&gt;Problem Statement:&lt;/b&gt;&lt;br /&gt;Write a program that takes N numbers as input, stores them in both an &lt;b&gt;array&lt;/b&gt; and a &lt;b&gt;vector&lt;/b&gt;, and computes the sum of elements.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;✅ Solution Using an&amp;nbsp;Array&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    int N;
    cout &amp;lt;&amp;lt; &quot;Enter number of elements: &quot;;
    cin &amp;gt;&amp;gt; N;
    
    int arr[N]; // Fixed-size array
    cout &amp;lt;&amp;lt; &quot;Enter &quot; &amp;lt;&amp;lt; N &amp;lt;&amp;lt; &quot; numbers: &quot;;
    for(int i = 0; i &amp;lt; N; i++) {
        cin &amp;gt;&amp;gt; arr[i];
    }
    int sum = 0;
    for(int i = 0; i &amp;lt; N; i++) {
        sum += arr[i];
    }
    cout &amp;lt;&amp;lt; &quot;Sum using array: &quot; &amp;lt;&amp;lt; sum &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Code Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;int arr[N]; &amp;rarr; Declares a &lt;b&gt;fixed-size&lt;/b&gt; array.&lt;/li&gt;
&lt;li&gt;cin &amp;gt;&amp;gt; arr[i]; &amp;rarr; Reads N elements into the array.&lt;/li&gt;
&lt;li&gt;sum += arr[i]; &amp;rarr; Iterates through the array to compute the sum.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;✅ Solution Using a Vector (Fixed-Size Approach)&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    int N;
    int sum = 0;

    cout &amp;lt;&amp;lt; &quot;Enter number N: &quot;;
    cin &amp;gt;&amp;gt; N;

    vector&amp;lt;int&amp;gt; myvector(N); // Declare a vector with N elements

    for (int i = 0; i &amp;lt; N; i++) {
        cout &amp;lt;&amp;lt; &quot;Enter element &quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; &quot; out of &quot; &amp;lt;&amp;lt; N &amp;lt;&amp;lt; &quot;: &quot;;
        cin &amp;gt;&amp;gt; myvector[i];
        sum += myvector[i]; // Compute the sum
    }

    cout &amp;lt;&amp;lt; &quot;Sum of vector is &quot; &amp;lt;&amp;lt; sum &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Code Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;vector&amp;lt;int&amp;gt; myvector(N); &amp;rarr; Declares a &lt;b&gt;vector with a fixed size of &lt;/b&gt;&lt;b&gt;N&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;cin &amp;gt;&amp;gt; myvector[i]; &amp;rarr; Reads N elements dynamically.&lt;/li&gt;
&lt;li&gt;sum += myvector[i]; &amp;rarr; Iterates through the vector to compute the sum.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;✅ Advantages:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;✔ Simple and easy to understand&lt;br /&gt;✔ No need for push_back() since size is fixed&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;❌ Disadvantages:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;✘ Requires N to be known beforehand&lt;br /&gt;✘ If N is too large, unnecessary memory is allocated&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;✅ &lt;b&gt;Solution Using a Vector (Dynamic Approach)&lt;/b&gt;&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
using namespace std;

int main() {
    int N;
    int sum = 0;
    vector&amp;lt;int&amp;gt; myvector; // Declare an empty vector

    cout &amp;lt;&amp;lt; &quot;Enter number N: &quot;;
    cin &amp;gt;&amp;gt; N;

    for (int i = 0; i &amp;lt; N; i++) {
        int value;
        cout &amp;lt;&amp;lt; &quot;Enter element &quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; &quot; out of &quot; &amp;lt;&amp;lt; N &amp;lt;&amp;lt; &quot;: &quot;;
        cin &amp;gt;&amp;gt; value;
        myvector.push_back(value); // Dynamically add elements
        sum += value;
    }

    cout &amp;lt;&amp;lt; &quot;Sum of vector is &quot; &amp;lt;&amp;lt; sum &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Code Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;vector&amp;lt;int&amp;gt; myvector; &amp;rarr; Declares an &lt;b&gt;empty vector&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;myvector.push_back(value); &amp;rarr; Dynamically adds elements to the vector.&lt;/li&gt;
&lt;li&gt;sum += value; &amp;rarr; Computes the sum during input.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;✅ Advantages:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;✔ Can handle unknown or varying N&lt;br /&gt;✔ More memory efficient if N changes frequently&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;❌ Disadvantages:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;✘ push_back() can be slower due to memory reallocation&lt;br /&gt;✘ Uses more memory in some cases due to dynamic resizing&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;  Output&amp;nbsp;Example&lt;/h3&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;csharp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Enter number N: 5  
Enter element 0 out of 5: 2  
Enter element 1 out of 5: 4  
Enter element 2 out of 5: 6  
Enter element 3 out of 5: 8  
Enter element 4 out of 5: 10  
Sum of vector is 30&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;&amp;nbsp;&lt;/h4&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;</description>
      <category>C++ Beginner</category>
      <category>C++</category>
      <category>c++stl</category>
      <category>c++데이터구조</category>
      <category>C++배열</category>
      <category>c++벡터</category>
      <category>CPP</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/42</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp013-Arrays-vs-Vectors-in-C-Understanding-the-Differences-with-Examples#entry42comment</comments>
      <pubDate>Wed, 26 Feb 2025 21:19:36 +0900</pubDate>
    </item>
    <item>
      <title>cpp_012: Introduction to Vectors in&amp;nbsp;C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp012-Introduction-to-Vectors-in-C</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Vectors in C++ provide a more flexible alternative to arrays. They are part of the &lt;b&gt;Standard Template Library (STL)&lt;/b&gt; and offer dynamic resizing, built-in functions, and better memory management. In this lesson, we&amp;rsquo;ll explore what vectors are, how they differ from arrays, and compare them to Python lists.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. What is a&amp;nbsp;Vector?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A &lt;b&gt;vector&lt;/b&gt; is a dynamic array that automatically resizes as elements are added or removed. Unlike arrays, which have a fixed size, vectors grow and shrink as needed.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To use vectors in C++, you must include the &amp;lt;vector&amp;gt; header:&lt;/p&gt;
&lt;pre class=&quot;autoit&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;vector&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Differences Between Vectors and&amp;nbsp;Arrays&lt;/h3&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;932&quot; data-origin-height=&quot;216&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/eyOBGx/btsMkDFaqKR/arhoQLYjRWsOZRKo5vH041/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/eyOBGx/btsMkDFaqKR/arhoQLYjRWsOZRKo5vH041/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/eyOBGx/btsMkDFaqKR/arhoQLYjRWsOZRKo5vH041/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FeyOBGx%2FbtsMkDFaqKR%2FarhoQLYjRWsOZRKo5vH041%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;932&quot; height=&quot;216&quot; data-origin-width=&quot;932&quot; data-origin-height=&quot;216&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Declaring and Initializing Vectors&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Vectors are defined using the std::vector keyword.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Basic Syntax&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;  // Include the vector library

using namespace std;

int main() {
    vector&amp;lt;int&amp;gt; numbers; // Declaring an empty vector
    vector&amp;lt;int&amp;gt; predefined = {10, 20, 30, 40}; // Declaring and initializing

    cout &amp;lt;&amp;lt; &quot;First element: &quot; &amp;lt;&amp;lt; predefined[0] &amp;lt;&amp;lt; endl; // Accessing elements
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;sql&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;First element: 10&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Adding and Removing&amp;nbsp;Elements&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Vectors support dynamic modification using functions like&amp;nbsp;.push_back() and&amp;nbsp;.pop_back().&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;

using namespace std;

int main() {
    vector&amp;lt;int&amp;gt; numbers;

    numbers.push_back(10); // Adds 10 to the vector
    numbers.push_back(20); // Adds 20 to the vector
    numbers.push_back(30);

    cout &amp;lt;&amp;lt; &quot;Vector size: &quot; &amp;lt;&amp;lt; numbers.size() &amp;lt;&amp;lt; endl; // Prints size

    numbers.pop_back(); // Removes the last element (30)
    cout &amp;lt;&amp;lt; &quot;New size after pop: &quot; &amp;lt;&amp;lt; numbers.size() &amp;lt;&amp;lt; endl;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;gradle&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Vector size: 3  
New size after pop: 2&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4. Iterating Over a&amp;nbsp;Vector&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Vectors can be accessed using &lt;b&gt;loops&lt;/b&gt; or &lt;b&gt;iterators&lt;/b&gt;.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Using a for&amp;nbsp;loop&lt;/h3&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;

using namespace std;

int main() {
    vector&amp;lt;int&amp;gt; nums = {1, 2, 3, 4, 5};

    for (int i = 0; i &amp;lt; nums.size(); i++) {
        cout &amp;lt;&amp;lt; nums[i] &amp;lt;&amp;lt; &quot; &quot;;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;basic&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;1 2 3 4 5&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Using a for-each&amp;nbsp;loop&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;

using namespace std;

int main() {
    vector&amp;lt;int&amp;gt; nums = {1, 2, 3, 4, 5};

    for (int num : nums) {
        cout &amp;lt;&amp;lt; num &amp;lt;&amp;lt; &quot; &quot;;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;basic&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;1 2 3 4 5&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;5. Comparison with Python&amp;nbsp;Lists&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Vectors in C++ are similar to Python lists because they allow dynamic resizing.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Python List&amp;nbsp;Example&lt;/h3&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;numbers = [10, 20, 30]
numbers.append(40)  # Equivalent to push_back()
print(numbers)  # [10, 20, 30, 40]

numbers.pop()  # Equivalent to pop_back()
print(numbers)  # [10, 20, 30]&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;json&quot; data-code-block-lang=&quot;csharp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;[10, 20, 30, 40]  
[10, 20, 30]&lt;/code&gt;&lt;/pre&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;936&quot; data-origin-height=&quot;176&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/IK5iP/btsMmGNLOzR/ee1V98H85QVFuiJH0TYzeK/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/IK5iP/btsMmGNLOzR/ee1V98H85QVFuiJH0TYzeK/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/IK5iP/btsMmGNLOzR/ee1V98H85QVFuiJH0TYzeK/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FIK5iP%2FbtsMmGNLOzR%2Fee1V98H85QVFuiJH0TYzeK%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;936&quot; height=&quot;176&quot; data-origin-width=&quot;936&quot; data-origin-height=&quot;176&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;h3 data-ke-size=&quot;size23&quot;&gt;7. Two-Dimensional Vectors&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Vectors can store other vectors, just like a 2D array.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;

using namespace std;

int main() {
    vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    cout &amp;lt;&amp;lt; &quot;Element at (1,1): &quot; &amp;lt;&amp;lt; matrix[1][1] &amp;lt;&amp;lt; endl;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;java&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Element at (1,1): 5&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Vectors are a powerful alternative to arrays in C++. They provide &lt;b&gt;dynamic resizing, built-in functions, and flexibility&lt;/b&gt;, making them a preferred choice for many applications. Unlike arrays, vectors manage memory automatically and prevent overflow issues.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Takeaways&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;✅ Use &lt;b&gt;vectors&lt;/b&gt; when you need a dynamic data structure.&lt;br /&gt;✅ Arrays are &lt;b&gt;faster&lt;/b&gt; but require manual memory management.&lt;br /&gt;✅ &lt;b&gt;Vectors in C++&lt;/b&gt; work similarly to &lt;b&gt;lists in Python&lt;/b&gt;.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>C++</category>
      <category>c++벡터</category>
      <category>vectors</category>
      <category>벡터</category>
      <category>코딩공부</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/41</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp012-Introduction-to-Vectors-in-C#entry41comment</comments>
      <pubDate>Mon, 17 Feb 2025 23:42:51 +0900</pubDate>
    </item>
    <item>
      <title>PyTorch_002_Implementing a Graph Convolutional Network (GCN)&amp;nbsp;Layer</title>
      <link>https://codeaddict.tistory.com/entry/PyTorch002Implementing-a-Graph-Convolutional-Network-GCN-Layer</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In the previous lesson, we introduced the mathematical foundation of Graph Convolutional Networks (GCNs). You can find the explanation of the GCN formula in the following link: [&lt;a href=&quot;https://medium.com/@staytechrich/graph-convolutional-networks-gcn-001-understanding-the-gcn-formula-step-by-step-a5e248c91ce0&quot; data-href=&quot;https://medium.com/@staytechrich/graph-convolutional-networks-gcn-001-understanding-the-gcn-formula-step-by-step-a5e248c91ce0&quot;&gt;link &lt;/a&gt;below].&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;a href=&quot;https://medium.com/@staytechrich/graph-convolutional-networks-gcn-001-understanding-the-gcn-formula-step-by-step-a5e248c91ce0&quot;&gt;https://medium.com/@staytechrich/graph-convolutional-networks-gcn-001-understanding-the-gcn-formula-step-by-step-a5e248c91ce0&lt;/a&gt;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, we will implement a GCN model in PyTorch, applying the concepts we learned. We will:&lt;br /&gt;✅ Compute the degree matrix D.&lt;br /&gt;✅ Compute the normalized adjacency matrix A-hat.&lt;br /&gt;✅ Implement a GCN layer.&lt;br /&gt;✅ Build a simple GCN model with two layers.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The core operation in GCNs follows this formula:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;252&quot; data-origin-height=&quot;45&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/cyTEnm/btsMlFBXubn/B5Y1Cf28U0mfKTEvqwlJEK/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/cyTEnm/btsMlFBXubn/B5Y1Cf28U0mfKTEvqwlJEK/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/cyTEnm/btsMlFBXubn/B5Y1Cf28U0mfKTEvqwlJEK/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FcyTEnm%2FbtsMlFBXubn%2FB5Y1Cf28U0mfKTEvqwlJEK%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;252&quot; height=&quot;45&quot; data-origin-width=&quot;252&quot; data-origin-height=&quot;45&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;where:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;A-hat (A^) is the normalized adjacency matrix.&lt;/li&gt;
&lt;li&gt;X is the input feature matrix.&lt;/li&gt;
&lt;li&gt;W is the learnable weight matrix.&lt;/li&gt;
&lt;li&gt;H is the output after applying the graph convolution operation.&lt;/li&gt;
&lt;li&gt;&amp;sigma;(sigma) is the activation function (e.g., ReLU).&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s implement this step by step:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s implement this step by step:&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import torch
import torch.nn.functional as F

def compute_degree_matrix(A):
    &quot;&quot;&quot;Computes the degree matrix D from adjacency matrix A.&quot;&quot;&quot;
    degrees = torch.sum(A, dim=1)
    D = torch.diag(degrees)
    return D

def normalize_adjacency(A):
    &quot;&quot;&quot;Computes the normalized adjacency matrix A_hat = D^(-1/2) * A * D^(-1/2).&quot;&quot;&quot;
    D = compute_degree_matrix(A)
    D_inv_sqrt = torch.diag(torch.pow(torch.diag(D), -0.5))
    A_hat = D_inv_sqrt @ A @ D_inv_sqrt
    return A_hat


&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;A. Computing the Degree Matrix&amp;nbsp;(D)&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The &lt;b&gt;degree matrix (D)&lt;/b&gt; is a diagonal matrix where each diagonal element represents the sum of connections (or edges) for each node in the adjacency matrix.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Mathematically, if &lt;b&gt;A&lt;/b&gt; is the adjacency matrix, the degree matrix &lt;b&gt;D&lt;/b&gt; is computed as:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;179&quot; data-origin-height=&quot;85&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/dHaQDt/btsMlo8fcMj/GlalFSIQJXy4oQXBX5ltG0/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/dHaQDt/btsMlo8fcMj/GlalFSIQJXy4oQXBX5ltG0/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/dHaQDt/btsMlo8fcMj/GlalFSIQJXy4oQXBX5ltG0/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FdHaQDt%2FbtsMlo8fcMj%2FGlalFSIQJXy4oQXBX5ltG0%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;179&quot; height=&quot;85&quot; data-origin-width=&quot;179&quot; data-origin-height=&quot;85&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;This means that each diagonal element of &lt;b&gt;D&lt;/b&gt; contains the total number of edges connected to a given node.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Explanation:&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;torch.sum(A, dim=1)&lt;/b&gt;: Summing along axis=1 (rows) gives the degree of each node.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;torch.diag(degrees)&lt;/b&gt;: Converts this degree vector into a diagonal matrix.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;B. Computing the Normalized Adjacency Matrix&amp;nbsp;(A^)&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To stabilize training and ensure proper feature propagation, we normalize the adjacency matrix &lt;b&gt;A&lt;/b&gt;. The normalized adjacency matrix &lt;b&gt;A^&lt;/b&gt; is computed as:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;214&quot; data-origin-height=&quot;56&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/Y3eB1/btsMlk5WYWF/wErZDRR5q6K4Kr0XZn3QE0/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/Y3eB1/btsMlk5WYWF/wErZDRR5q6K4Kr0XZn3QE0/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/Y3eB1/btsMlk5WYWF/wErZDRR5q6K4Kr0XZn3QE0/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FY3eB1%2FbtsMlk5WYWF%2FwErZDRR5q6K4Kr0XZn3QE0%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;214&quot; height=&quot;56&quot; data-origin-width=&quot;214&quot; data-origin-height=&quot;56&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;This normalization ensures that information is distributed more evenly across nodes.&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; data-code-block-lang=&quot;ruby&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;class GCNLayer(torch.nn.Module):
    def __init__(self, in_features, out_features):
        super(GCNLayer, self).__init__()
        self.W = torch.nn.Parameter(torch.randn(in_features, out_features))  # Learnable weights

    def forward(self, A, X):
        A_hat = normalize_adjacency(A)  # Compute A_hat
        H = A_hat @ X @ self.W  # Graph convolution operation
        return F.relu(H)  # Apply ReLU activation&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Explanation:&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Define a weight matrix &lt;/b&gt;&lt;b&gt;self.W&lt;/b&gt; that will be learned during training.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Compute the normalized adjacency matrix &lt;/b&gt;&lt;b&gt;A_hat&lt;/b&gt; using the function we defined earlier.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Multiply &lt;/b&gt;&lt;b&gt;A_hat @ X @ W&lt;/b&gt; to perform the graph convolution operation.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Apply &lt;/b&gt;&lt;b&gt;ReLU&lt;/b&gt;&lt;b&gt; activation function&lt;/b&gt; to introduce non-linearity.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Defining the GCN&amp;nbsp;Model&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A &lt;b&gt;GCN model&lt;/b&gt; consists of multiple layers stacked on top of each other. Each layer extracts higher-level node representations.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here, we define a &lt;b&gt;two-layer GCN&lt;/b&gt;:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;The &lt;b&gt;first layer&lt;/b&gt; transforms input features into a hidden representation.&lt;/li&gt;
&lt;li&gt;The &lt;b&gt;second layer&lt;/b&gt; maps hidden representations to output features.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;ruby&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;class GCN(torch.nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(GCN, self).__init__()
        self.gcn1 = GCNLayer(input_dim, hidden_dim)
        self.gcn2 = GCNLayer(hidden_dim, output_dim)

    def forward(self, A, X):
        H1 = self.gcn1(A, X)  # First GCN layer
        H2 = self.gcn2(A, H1)  # Second GCN layer
        return H2&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;First layer (&lt;/b&gt;&lt;b&gt;gcn1&lt;/b&gt;&lt;b&gt;)&lt;/b&gt; maps input features to a hidden dimension.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Second layer (&lt;/b&gt;&lt;b&gt;gcn2&lt;/b&gt;&lt;b&gt;)&lt;/b&gt; maps hidden features to the final output.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Pass adjacency matrix &lt;/b&gt;&lt;b&gt;A&lt;/b&gt;&lt;b&gt; and features &lt;/b&gt;&lt;b&gt;X&lt;/b&gt;&lt;b&gt; through both layers.&lt;/b&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Running the GCN&amp;nbsp;Model&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s test our model with some sample data:&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Example Graph:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Adjacency matrix (A)&lt;/b&gt; representing a simple 3-node graph.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Feature matrix (X)&lt;/b&gt; with two features per node.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;# Example adjacency matrix (3 nodes)
A = torch.tensor([[1, 1, 0],
                  [1, 1, 1],
                  [0, 1, 1]], dtype=torch.float32)

# Example feature matrix (3 nodes, 2 features)
X = torch.tensor([[1, 2],
                  [3, 4],
                  [5, 6]], dtype=torch.float32)

# Define the model
gcn = GCN(input_dim=2, hidden_dim=4, output_dim=2)

# Forward pass
output = gcn(A, X)
print(&quot;Final GCN Output:\n&quot;, output)&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;6. Step-by-Step Execution&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s walk through what happens when we execute gcn(A, X):&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Compute A^ (Normalized Adjacency Matrix)&lt;/b&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Compute the degree matrix D.&lt;/li&gt;
&lt;li&gt;Compute D^(-1/2).&lt;/li&gt;
&lt;li&gt;Normalize A to get A^.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. First GCN Layer (&lt;/b&gt;&lt;b&gt;gcn1&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Compute &lt;b&gt;H1 = ReLU(A^ X W1)&lt;/b&gt; where W1 is the weight matrix of the first layer.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Second GCN Layer (&lt;/b&gt;&lt;b&gt;gcn2&lt;/b&gt;&lt;b&gt;)&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Compute &lt;b&gt;H2 = ReLU(A^ H1 W2)&lt;/b&gt; where W2 is the weight matrix of the second layer.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. Final Output&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;H2 is returned as the final node representations.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this lesson, we implemented a simple Graph Convolutional Network (GCN) in PyTorch. We followed the mathematical formula introduced in the previous lesson and broke it down into:&lt;br /&gt;✔️ Computing the degree matrix D.&lt;br /&gt;✔️ Computing the normalized adjacency matrix A-hat(A^).&lt;br /&gt;✔️ Implementing a GCN layer.&lt;br /&gt;✔️ Defining a two-layer GCN model.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In the next lesson, we will train this model on real graph data!  &lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Pytorch Beginner</category>
      <category>DeepLearning</category>
      <category>GCN</category>
      <category>gcn튜토리얼</category>
      <category>graphconvolutionalnetwork</category>
      <category>pytorch</category>
      <category>딥러닝</category>
      <category>인공지능</category>
      <category>파이토치</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/40</guid>
      <comments>https://codeaddict.tistory.com/entry/PyTorch002Implementing-a-Graph-Convolutional-Network-GCN-Layer#entry40comment</comments>
      <pubDate>Mon, 17 Feb 2025 16:54:32 +0900</pubDate>
    </item>
    <item>
      <title>Graph_Convolutional_Networks (GCN)_001 _ Understanding the GCN Formula Step by&amp;nbsp;Step</title>
      <link>https://codeaddict.tistory.com/entry/GraphConvolutionalNetworks-GCN001-Understanding-the-GCN-Formula-Step-by-Step</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Introduction&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this post, we will break down the fundamental Graph Convolutional Network (GCN) formula with a simple example. We will walk through each component, including the adjacency matrix, degree matrix, normalization, and feature transformations. By the end of this lesson, you&amp;rsquo;ll have a clear understanding of the basic mathematical operations behind GCNs.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In a &lt;b&gt;Graph Convolutional Network (GCN)&lt;/b&gt;, the key transformation is given by the following formula:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;924&quot; data-origin-height=&quot;345&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/bCNDXZ/btsMlnONeLJ/IeHKAKvHajXWq5jOgLvRq0/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/bCNDXZ/btsMlnONeLJ/IeHKAKvHajXWq5jOgLvRq0/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/bCNDXZ/btsMlnONeLJ/IeHKAKvHajXWq5jOgLvRq0/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbCNDXZ%2FbtsMlnONeLJ%2FIeHKAKvHajXWq5jOgLvRq0%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;924&quot; height=&quot;345&quot; data-origin-width=&quot;924&quot; data-origin-height=&quot;345&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;
&lt;/p&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, let's go &lt;b&gt;step by step&lt;/b&gt; to understand how each part of this formula works in practice.&lt;/p&gt;
&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 1: Understanding the Graph Structure&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Consider a simple graph with three nodes:&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;lua&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;   (1) -- (2)
     \    /
      \  /
       (3)&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The &lt;b&gt;adjacency matrix (A)&lt;/b&gt; represents the connections between nodes:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;188&quot; data-origin-height=&quot;120&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/bE3JY9/btsMkABcGim/Wgaw7nkdnDd6W8WkB0xwv0/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/bE3JY9/btsMkABcGim/Wgaw7nkdnDd6W8WkB0xwv0/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/bE3JY9/btsMkABcGim/Wgaw7nkdnDd6W8WkB0xwv0/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbE3JY9%2FbtsMkABcGim%2FWgaw7nkdnDd6W8WkB0xwv0%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;188&quot; height=&quot;120&quot; data-origin-width=&quot;188&quot; data-origin-height=&quot;120&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The rows and columns correspond to nodes.&lt;/li&gt;
&lt;li&gt;A value of &lt;b&gt;1&lt;/b&gt; indicates a connection between nodes, while &lt;b&gt;0&lt;/b&gt; means no direct connection.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 2: Adding Self-Loops&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;We add self-loops to each node by introducing an &lt;b&gt;identity matrix (I)&lt;/b&gt;:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;586&quot; data-origin-height=&quot;122&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/blFKEu/btsMmdY2W9x/GB8ri1dnxqT5j0wSPsvkmK/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/blFKEu/btsMmdY2W9x/GB8ri1dnxqT5j0wSPsvkmK/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/blFKEu/btsMmdY2W9x/GB8ri1dnxqT5j0wSPsvkmK/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FblFKEu%2FbtsMmdY2W9x%2FGB8ri1dnxqT5j0wSPsvkmK%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;586&quot; height=&quot;122&quot; data-origin-width=&quot;586&quot; data-origin-height=&quot;122&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;Now, each node is also connected to itself.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 3: Computing the Degree&amp;nbsp;Matrix&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The &lt;b&gt;degree matrix (D&amp;rsquo;)&lt;/b&gt; is a diagonal matrix where each diagonal element represents the sum of connections for that node:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;For our graph, each node is connected to &lt;b&gt;two other nodes&lt;/b&gt; and also has a &lt;b&gt;self-loop&lt;/b&gt; (since we added the identity matrix I). So, each node has a total of &lt;b&gt;3 connections&lt;/b&gt;.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Why are only diagonal elements&amp;nbsp;nonzero?&lt;/h4&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The &lt;b&gt;degree matrix&lt;/b&gt; is &lt;b&gt;always diagonal&lt;/b&gt; because it only counts &lt;b&gt;the number of edges per node&lt;/b&gt; &amp;mdash; not their relationships with other nodes.&lt;/li&gt;
&lt;li&gt;The &lt;b&gt;off-diagonal elements are always zero&lt;/b&gt; because they do not represent any direct connection count, only the total degree of each node.&lt;/li&gt;
&lt;li&gt;Row 1: Node 1 is connected to &lt;b&gt;Node 2, Node 3, and itself&lt;/b&gt; &amp;rarr; &lt;b&gt;Total = 3&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;Row 2: Node 2 is connected to &lt;b&gt;Node 1, Node 3, and itself&lt;/b&gt; &amp;rarr; &lt;b&gt;Total = 3&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;Row 3: Node 3 is connected to &lt;b&gt;Node 1, Node 2, and itself&lt;/b&gt; &amp;rarr; &lt;b&gt;Total = 3&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Thus, the &lt;b&gt;degree matrix&lt;/b&gt; is:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;282&quot; data-origin-height=&quot;130&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/mMN6U/btsMkwr9zDA/iB2hVRdiwKnDo7ilPseCuk/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/mMN6U/btsMkwr9zDA/iB2hVRdiwKnDo7ilPseCuk/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/mMN6U/btsMkwr9zDA/iB2hVRdiwKnDo7ilPseCuk/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FmMN6U%2FbtsMkwr9zDA%2FiB2hVRdiwKnDo7ilPseCuk%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;282&quot; height=&quot;130&quot; data-origin-width=&quot;282&quot; data-origin-height=&quot;130&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;Each &lt;b&gt;diagonal element&lt;/b&gt; (3) represents the &lt;b&gt;sum of connections&lt;/b&gt; for that node, and &lt;b&gt;of&lt;/b&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 4: Normalizing the Adjacency Matrix&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;We compute the inverse square root of the degree matrix:&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;690&quot; data-origin-height=&quot;558&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/ucqJm/btsMkxdwfaQ/YCTrUqdHgRnw048K6sUF20/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/ucqJm/btsMkxdwfaQ/YCTrUqdHgRnw048K6sUF20/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/ucqJm/btsMkxdwfaQ/YCTrUqdHgRnw048K6sUF20/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FucqJm%2FbtsMkxdwfaQ%2FYCTrUqdHgRnw048K6sUF20%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;690&quot; height=&quot;558&quot; data-origin-width=&quot;690&quot; data-origin-height=&quot;558&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 5: Applying Features&amp;nbsp;&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;At this stage, we introduce the &lt;b&gt;feature matrix X&lt;/b&gt;, which represents the &lt;b&gt;features of each node&lt;/b&gt; in our graph.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;What is the feature matrix&amp;nbsp;X?&lt;/h4&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Each &lt;b&gt;row&lt;/b&gt; in X corresponds to a &lt;b&gt;node&lt;/b&gt; in our graph.&lt;/li&gt;
&lt;li&gt;Each &lt;b&gt;column&lt;/b&gt; in X represents a &lt;b&gt;feature&lt;/b&gt; associated with the node.&lt;/li&gt;
&lt;li&gt;The values in X are &lt;b&gt;imaginary/random&lt;/b&gt; for this example and do not represent real-world data. They are just chosen to make the calculations clear.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Assume we have &lt;b&gt;3 nodes&lt;/b&gt;, and each node has &lt;b&gt;2 features&lt;/b&gt; (e.g., some numerical properties like &amp;ldquo;height&amp;rdquo; and &amp;ldquo;weight&amp;rdquo; in a social network or &amp;ldquo;temperature&amp;rdquo; and &amp;ldquo;humidity&amp;rdquo; in a sensor network).&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;We define our &lt;b&gt;feature matrix X&lt;/b&gt; as follows:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;202&quot; data-origin-height=&quot;134&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/RulPI/btsMlh81P36/PuNMLEx4IQiLoyporb8751/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/RulPI/btsMlh81P36/PuNMLEx4IQiLoyporb8751/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/RulPI/btsMlh81P36/PuNMLEx4IQiLoyporb8751/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FRulPI%2FbtsMlh81P36%2FPuNMLEx4IQiLoyporb8751%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;202&quot; height=&quot;134&quot; data-origin-width=&quot;202&quot; data-origin-height=&quot;134&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s what each value represents:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Node 1:&lt;/b&gt; Feature 1 = &lt;b&gt;1&lt;/b&gt;, Feature 2 = &lt;b&gt;2&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Node 2:&lt;/b&gt; Feature 1 = &lt;b&gt;3&lt;/b&gt;, Feature 2 = &lt;b&gt;4&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Node 3:&lt;/b&gt; Feature 1 = &lt;b&gt;5&lt;/b&gt;, Feature 2 = &lt;b&gt;6&lt;/b&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Important Notes:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;These values are &lt;b&gt;arbitrary&lt;/b&gt; and just for illustration. In real applications, these features could represent anything from &lt;b&gt;user preferences&lt;/b&gt; in a social network to &lt;b&gt;pixel values&lt;/b&gt; in an image.&lt;/li&gt;
&lt;li&gt;The &lt;b&gt;number of columns&lt;/b&gt; in X (here, &lt;b&gt;2&lt;/b&gt;) represents the &lt;b&gt;input feature dimension&lt;/b&gt; &amp;mdash; it defines how many numerical properties each node has.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now that we have our feature matrix, the next step is to apply the &lt;b&gt;graph convolutional operation&lt;/b&gt; using weights.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 6: Multiplying with A^ (Normalized Adjacency Matrix)&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now that we have our &lt;b&gt;feature matrix X&lt;/b&gt;, the next step is to perform the graph convolution operation by multiplying X with the normalized adjacency matrix A^(A- hat).&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;What is&amp;nbsp;A^?&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;A- hat is a modified version of the adjacency matrix that includes &lt;b&gt;self-loops &lt;/b&gt;as described in previous steps&lt;/li&gt;
&lt;li&gt;It helps in aggregating information from each node&amp;rsquo;s neighbors &lt;b&gt;including itself&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;The purpose of multiplying with A-hat is to allow nodes to receive feature information from their neighbors.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;For our example, the multiplication looks like this:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;193&quot; data-origin-height=&quot;123&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/n3qlh/btsMmrCIWIZ/zy3koK7Flrk13Ov0QikMUk/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/n3qlh/btsMmrCIWIZ/zy3koK7Flrk13Ov0QikMUk/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/n3qlh/btsMmrCIWIZ/zy3koK7Flrk13Ov0QikMUk/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fn3qlh%2FbtsMmrCIWIZ%2Fzy3koK7Flrk13Ov0QikMUk%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;193&quot; height=&quot;123&quot; data-origin-width=&quot;193&quot; data-origin-height=&quot;123&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;h3 data-ke-size=&quot;size23&quot;&gt;What does this multiplication do?&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;It &lt;b&gt;aggregates features from neighboring nodes&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Since each node has 2 direct neighbors (plus itself), the sum results in &lt;b&gt;(3,4) for each row&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;This shows that every node&amp;rsquo;s updated feature is influenced by &lt;b&gt;the sum of itself and its neighbors&amp;rsquo; features&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 7: Applying the Weight Matrix&amp;nbsp;W&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, we introduce the &lt;b&gt;weight matrix W&lt;/b&gt;, which is a trainable parameter in a GCN:&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;203&quot; data-origin-height=&quot;78&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/6JuDH/btsMmganoHD/zcYlXZshd1dmCKdWk4uNvk/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/6JuDH/btsMmganoHD/zcYlXZshd1dmCKdWk4uNvk/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/6JuDH/btsMmganoHD/zcYlXZshd1dmCKdWk4uNvk/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2F6JuDH%2FbtsMmganoHD%2FzcYlXZshd1dmCKdWk4uNvk%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;203&quot; height=&quot;78&quot; data-origin-width=&quot;203&quot; data-origin-height=&quot;78&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;These numbers are random and do not come from real data.&lt;/b&gt; They are just used for illustration purposes.&lt;/li&gt;
&lt;li&gt;In a real GCN, these numbers are &lt;b&gt;initialized randomly&lt;/b&gt; and then &lt;b&gt;updated&lt;/b&gt; during training using backpropagation.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;What is the Weight Matrix&amp;nbsp;W?&lt;/h4&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;W is a matrix that transforms the feature representations of nodes.&lt;/li&gt;
&lt;li&gt;It &lt;b&gt;learns&lt;/b&gt; to extract meaningful patterns from node features over time.&lt;/li&gt;
&lt;li&gt;Each element in W represents how important a particular input feature is in transforming node embeddings.&lt;/li&gt;
&lt;li&gt;W is &lt;b&gt;learned during training&lt;/b&gt; and helps in transforming the features into a new space.&lt;/li&gt;
&lt;li&gt;The &lt;b&gt;rows in W&lt;/b&gt; correspond to the &lt;b&gt;input feature dimension (2 features per node in X)&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;The &lt;b&gt;columns in W&lt;/b&gt; correspond to the &lt;b&gt;new transformed feature dimension&lt;/b&gt; (which could be different).&lt;/li&gt;
&lt;/ul&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;695&quot; data-origin-height=&quot;521&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/o3qF8/btsMlXa31BR/4KXslSI05dq3uoZqKgzFu1/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/o3qF8/btsMlXa31BR/4KXslSI05dq3uoZqKgzFu1/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/o3qF8/btsMlXa31BR/4KXslSI05dq3uoZqKgzFu1/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fo3qF8%2FbtsMlXa31BR%2F4KXslSI05dq3uoZqKgzFu1%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;695&quot; height=&quot;521&quot; data-origin-width=&quot;695&quot; data-origin-height=&quot;521&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;h4 data-ke-size=&quot;size20&quot;&gt;How are the values in W selected in real applications?&lt;/h4&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Initially, they are set randomly (e.g., small random values close to zero).&lt;/li&gt;
&lt;li&gt;As the model trains, an optimization algorithm (like &lt;b&gt;Gradient Descent&lt;/b&gt;) adjusts these values to minimize the loss.&lt;/li&gt;
&lt;li&gt;Over time, W learns to capture the important relationships between node features and their labels (or other predictive targets).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 8: Understanding the Final Transformed Features&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;At this point, each node&amp;rsquo;s features have been &lt;b&gt;updated&lt;/b&gt; based on:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Its own features&lt;/b&gt; (from X)&lt;/li&gt;
&lt;li&gt;&lt;b&gt;The features of its neighbors&lt;/b&gt; (aggregated using A-hat)&lt;/li&gt;
&lt;li&gt;&lt;b&gt;The learned transformation&lt;/b&gt; (from W)&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Takeaways&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The &lt;b&gt;graph convolution operation&lt;/b&gt; allows each node to gather information from its neighbors.&lt;/li&gt;
&lt;li&gt;The &lt;b&gt;weight matrix W&lt;/b&gt; helps the model &lt;b&gt;learn patterns&lt;/b&gt; in the data.&lt;/li&gt;
&lt;li&gt;The output matrix represents the &lt;b&gt;new features for each node&lt;/b&gt;, which can now be used for &lt;b&gt;classification, clustering, or further graph learning tasks&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 6: Applying the Activation Function&lt;/h3&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;824&quot; data-origin-height=&quot;516&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/3BlWM/btsMlo710gi/ZvBwdjT2Jf2oEGbceapnRk/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/3BlWM/btsMlo710gi/ZvBwdjT2Jf2oEGbceapnRk/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/3BlWM/btsMlo710gi/ZvBwdjT2Jf2oEGbceapnRk/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2F3BlWM%2FbtsMlo710gi%2FZvBwdjT2Jf2oEGbceapnRk%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;824&quot; height=&quot;516&quot; data-origin-width=&quot;824&quot; data-origin-height=&quot;516&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion: Summary of Graph Convolutional Operation&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Start with the feature matrix X, where each row represents a node&amp;rsquo;s features.&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Multiply X with the normalized adjacency matrix A-hat(A^), aggregating neighboring node information.&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Multiply the result with a trainable weight matrix W to transform features.&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;(Optional) Apply an activation function like ReLU for non-linearity.&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Use the new features for tasks like node classification or link prediction.&lt;/b&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this post, we broke down the GCN formula step by step, starting with the graph structure and progressing through normalization, feature transformation, and activation. In the next lesson, we will implement this mathematically defined GCN as a simple model in &lt;b&gt;PyTorch (included in pytorch beginner catogory)&lt;/b&gt;.&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Deep Learning</category>
      <category>gcn tutorial</category>
      <category>gcn 튜토리얼</category>
      <category>graph convolutional networks</category>
      <category>graph neural networks</category>
      <category>그래프 컨볼루션 네트워크</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/39</guid>
      <comments>https://codeaddict.tistory.com/entry/GraphConvolutionalNetworks-GCN001-Understanding-the-GCN-Formula-Step-by-Step#entry39comment</comments>
      <pubDate>Mon, 17 Feb 2025 14:38:47 +0900</pubDate>
    </item>
    <item>
      <title>threading_001: Introduction to Python&amp;nbsp;Threads</title>
      <link>https://codeaddict.tistory.com/entry/threading001-Introduction-to-Python-Threads</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this tutorial, we will explore the basics of threading in Python. We will break down simple examples using the threading module and progressively dive into more complex scenarios.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Overview&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Threading allows concurrent execution of multiple tasks (or threads) within a program. Python&amp;rsquo;s built-in threading module makes it easy to handle threads and boost performance for I/O-bound tasks.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. Simple Example: Running Multiple&amp;nbsp;Threads&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The example below shows how to create and run two threads concurrently:&lt;/p&gt;
&lt;pre class=&quot;pgsql&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import threading
import time

# Define a function to run in threads
def print_numbers():
    for i in range(5):
        print(f&quot;Number: {i}&quot;)
        time.sleep(1)  # Simulate a time-consuming task
# Create two threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_numbers)
# Start the threads
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
print(&quot;Both threads have finished execution.&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;We define a function print_numbers() that prints numbers from 0 to 4 with a 1-second delay between prints.&lt;/li&gt;
&lt;li&gt;We create two threads using threading.Thread and pass the target function.&lt;/li&gt;
&lt;li&gt;The threads are started with start() and waited upon using join().&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Example 2: Passing Arguments to&amp;nbsp;Threads&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, let&amp;rsquo;s modify the code to pass arguments to the thread functions:&lt;/p&gt;
&lt;pre class=&quot;pgsql&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import threading
import time

# Define a function with arguments
def print_numbers(name, count):
    for i in range(count):
        print(f&quot;{name} - Number: {i}&quot;)
        time.sleep(1)
# Create threads with different arguments
thread1 = threading.Thread(target=print_numbers, args=(&quot;Thread1&quot;, 3))
thread2 = threading.Thread(target=print_numbers, args=(&quot;Thread2&quot;, 5))
# Start the threads
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
print(&quot;All threads have completed.&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;The print_numbers function now takes two arguments: name and count.&lt;/li&gt;
&lt;li&gt;We pass these arguments using the args parameter when creating the threads.&lt;/li&gt;
&lt;li&gt;Each thread behaves independently, printing its own sequence of numbers.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Example: Inheriting from threading.Thread&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Another approach is to create a custom class by inheriting from threading.Thread. Below is a simple example:&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import threading
import time
from typing import Dict, List

class CustomThread(threading.Thread):
    thread_store: Dict[str, List[threading.Thread]] = {}
    def __init__(self, name: str, count: int):
        super().__init__()
        self.name = name
        self.count = count
    def run(self):
        &quot;&quot;&quot;The entry point for the thread.&quot;&quot;&quot;
        for i in range(self.count):
            print(f&quot;{self.name} - Number: {i}&quot;)
            time.sleep(1)
# Create and start threads
thread1 = CustomThread(&quot;Thread1&quot;, 3)
thread2 = CustomThread(&quot;Thread2&quot;, 5)
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
print(&quot;Custom threads have completed.&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Class Definition:&lt;/b&gt; The CustomThread class inherits from threading.Thread.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Shared Resource:&lt;/b&gt; thread_store is a class-level dictionary for managing threads if needed in more complex cases.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Initialization:&lt;/b&gt; The __init__ method calls super().__init__() to ensure proper initialization of the thread.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Overriding &lt;/b&gt;&lt;b&gt;run()&lt;/b&gt;&lt;b&gt;:&lt;/b&gt; The run() method defines the code that will execute in the thread.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Creating and Starting Threads:&lt;/b&gt; We instantiate the custom threads and start them with start().&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Joining Threads:&lt;/b&gt; join() ensures that the main program waits for both threads to complete.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Pytorch Beginner</category>
      <category>backend</category>
      <category>multithreading</category>
      <category>python threading</category>
      <category>Thread</category>
      <category>멀티스레딩</category>
      <category>파이썬스레딩</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/38</guid>
      <comments>https://codeaddict.tistory.com/entry/threading001-Introduction-to-Python-Threads#entry38comment</comments>
      <pubDate>Sun, 9 Feb 2025 17:30:42 +0900</pubDate>
    </item>
    <item>
      <title>cpp_012: Multidimensional Arrays in&amp;nbsp;C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp012-Multidimensional-Arrays-in-C</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Multidimensional arrays are an extension of one-dimensional arrays, allowing you to store data in a grid-like structure. They are particularly useful for representing matrices, tables, or any data that requires multiple dimensions. In this lesson, we&amp;rsquo;ll explore how to declare, initialize, and use multidimensional arrays in C++. We&amp;rsquo;ll also cover how to input data into arrays using cin and handle early loop exits.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. What Are Multidimensional Arrays?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A multidimensional array is an array of arrays. For example, a 2D array can be thought of as a table with rows and columns, while a 3D array can be visualized as a cube with layers, rows, and columns.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Declaring and Initializing Multidimensional Arrays&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To declare a 2D array in C++, use the following syntax:&lt;/p&gt;
&lt;pre class=&quot;markdown&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;data_type array_name[rows][columns];&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Example:&lt;/h4&gt;
&lt;pre class=&quot;markdown&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;For a 3D array:&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;int cube[2][3][4] = {
    {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    },
    {
        {13, 14, 15, 16},
        {17, 18, 19, 20},
        {21, 22, 23, 24}
    }
};&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Accessing Elements in Multidimensional Arrays&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can access elements using nested loops. For example, to print a 2D array:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    // Declaring and initializing a 2D array
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    // Loop to traverse the 2D array and print its elements
    for (int i = 0; i &amp;lt; 2; i++) {   // Loop through rows
        for (int j = 0; j &amp;lt; 3; j++) {  // Loop through columns
            cout &amp;lt;&amp;lt; matrix[i][j] &amp;lt;&amp;lt; &quot; &quot;;  // Print each element
        }
        cout &amp;lt;&amp;lt; endl;  // Print a new line after each row
    }

    return 0;  // Return 0 to indicate successful execution
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4. Inputting Data into Arrays Using&amp;nbsp;cin&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can use cin to populate arrays with user input. Here&amp;rsquo;s how:&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;For a 1D&amp;nbsp;Array:&lt;/h4&gt;
&lt;pre class=&quot;abnf&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;int arr[5];
cout &amp;lt;&amp;lt; &quot;Enter 5 elements: &quot;;
for (int i = 0; i &amp;lt; 5; i++) {
    cin &amp;gt;&amp;gt; arr[i];
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Complete code:&lt;/h4&gt;
&lt;pre class=&quot;smali&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include&amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    int arr[5];  // Declare an array of size 5

    // Input values into the array
    cout &amp;lt;&amp;lt; &quot;Enter 5 integers: &quot;;
    for (int i = 0; i &amp;lt; 5; i++) {
        cin &amp;gt;&amp;gt; arr[i];  // Take input for each element of the array
    }

    // Output the elements of the array
    cout &amp;lt;&amp;lt; &quot;Array elements: &quot;;
    for (int i = 0; i &amp;lt; 5; i++) {
        cout &amp;lt;&amp;lt; arr[i] &amp;lt;&amp;lt; &quot; &quot;;  // Print each element followed by a space
    }
    cout &amp;lt;&amp;lt; endl;  // Print a new line after the array

    return 0;  // Return 0 to indicate successful execution
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;For a 2D&amp;nbsp;Array:&lt;/h4&gt;
&lt;pre class=&quot;markdown&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;int matrix[2][3];
cout &amp;lt;&amp;lt; &quot;Enter 6 elements (2 rows x 3 columns): &quot;;
for (int i = 0; i &amp;lt; 2; i++) {
    for (int j = 0; j &amp;lt; 3; j++) {
        cin &amp;gt;&amp;gt; matrix[i][j];
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Complete code:&lt;/h4&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include&amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    // Declare a 2D array with 2 rows and 3 columns
    int matrix[2][3];

    // Input elements into the matrix
    cout &amp;lt;&amp;lt; &quot;Enter 6 elements (2 rows x 3 columns): &quot;;
    for (int i = 0; i &amp;lt; 2; i++) {       // Loop through rows
        for (int j = 0; j &amp;lt; 3; j++) {   // Loop through columns
            cin &amp;gt;&amp;gt; matrix[i][j];  // Read input for each element
        }
    }

    // Output the elements of the matrix
    cout &amp;lt;&amp;lt; &quot;The matrix is:&quot; &amp;lt;&amp;lt; endl;
    for (int i = 0; i &amp;lt; 2; i++) {       // Loop through rows
        for (int j = 0; j &amp;lt; 3; j++) {   // Loop through columns
            cout &amp;lt;&amp;lt; matrix[i][j] &amp;lt;&amp;lt; &quot; &quot;;  // Print each element
        }
        cout &amp;lt;&amp;lt; endl;  // Print a new line after each row
    }

    return 0;  // Return 0 to indicate successful execution
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>2d arrays in c++</category>
      <category>c++ arrays</category>
      <category>C++ 배열</category>
      <category>Multidimensional Arrays</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/37</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp012-Multidimensional-Arrays-in-C#entry37comment</comments>
      <pubDate>Sat, 8 Feb 2025 15:09:29 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_005: Type Hinting in&amp;nbsp;Python</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate005-Type-Hinting-in-Python</link>
      <description>&lt;p data-ke-size=&quot;size16&quot;&gt;When writing Python code, you often need to make your code more readable and maintainable, especially for larger projects. This is where type hinting becomes essential. Type hints help you specify the expected types of variables, function arguments, and return values. Let&amp;rsquo;s explore how to use type hints effectively with simple examples.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Why Use Type&amp;nbsp;Hints?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Type hints help:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Improve code readability.&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Catch type-related errors during development.&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Provide better autocompletion and type checking in IDEs.&lt;/b&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Basic Type&amp;nbsp;Hints&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s how to annotate variable types and function signatures:&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;# Variable type hints
name: str = &quot;Alice&quot;
age: int = 30
is_active: bool = True

# Function with type hints
def greet(name: str) -&amp;gt; str:
    return f&quot;Hello, {name}!&quot;
print(greet(&quot;Bob&quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;name: str&lt;/b&gt;: Indicates that name is a string.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;age: int&lt;/b&gt;: Indicates that age is an integer.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;def greet(name: str) -&amp;gt; str&lt;/b&gt;: Specifies that the greet function takes a string argument and returns a string.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Type Hints with Collections&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can annotate lists, dictionaries, and other collections using the &lt;b&gt;List&lt;/b&gt; and &lt;b&gt;Dict&lt;/b&gt; types from the &lt;b&gt;typing&lt;/b&gt; module.&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;from typing import List, Dict

# List of integers
numbers: List[int] = [1, 2, 3, 4]
# Dictionary with string keys and integer values
data: Dict[str, int] = {&quot;apples&quot;: 5, &quot;oranges&quot;: 3}
print(numbers)
print(data)&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;List[int]&lt;/b&gt;: Specifies that numbers is a list containing integers.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Dict[str, int]&lt;/b&gt;: Indicates that data is a dictionary with string keys and integer values.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Type Hints for Functions with Multiple Arguments&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can use type hints to specify types for multiple arguments.&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;php&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;from typing import List

def calculate_sum(numbers: List[int]) -&amp;gt; int:
    return sum(numbers)
result = calculate_sum([10, 20, 30])
print(f&quot;Sum: {result}&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;numbers: List[int]&lt;/b&gt;: The function expects a list of integers.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;-&amp;gt; int&lt;/b&gt;: The function returns an integer.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Using Optional&amp;nbsp;Types&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Sometimes, a variable or function argument can be optional. Use &lt;b&gt;Optional&lt;/b&gt; to indicate this.&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;from typing import Optional

def greet(name: Optional[str] = None) -&amp;gt; str:
    if name:
        return f&quot;Hello, {name}!&quot;
    return &quot;Hello, Stranger!&quot;
print(greet())
print(greet(&quot;Alice&quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Optional[str]&lt;/b&gt;: Indicates that name can be either a string or None.&lt;/li&gt;
&lt;li&gt;The default value of None allows the argument to be optional.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>codereadability</category>
      <category>typehints</category>
      <category>타입힌트</category>
      <category>파이썬</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/36</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate005-Type-Hinting-in-Python#entry36comment</comments>
      <pubDate>Sat, 8 Feb 2025 01:47:57 +0900</pubDate>
    </item>
    <item>
      <title>Django REST Framework_004: erializers and Model-to-JSON Conversion</title>
      <link>https://codeaddict.tistory.com/entry/Django-REST-Framework004-erializers-and-Model-to-JSON-Conversion</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this lesson, we will dive deeper into Django REST Framework (DRF) serializers, which are a crucial component for converting complex data types, such as Django models, into Python data types that can be easily rendered into JSON, XML, or other content types. We will also explore the important methods and concepts related to serializers, and how they fit into the broader context of building RESTful APIs with Django.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;What is a Serializer?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A serializer in Django REST Framework is a component that allows you to convert complex data types (like Django models) into Python data types that can be easily rendered into JSON, XML, or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types after validating the incoming data.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In simpler terms, serializers help you:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Convert Django models to JSON&lt;/b&gt;: When you want to send data from your Django application to a client (e.g., a web browser or mobile app), serializers convert your Django model instances into JSON format.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Convert JSON to Django models&lt;/b&gt;: When you receive data from a client (e.g., a form submission), serializers validate the data and convert it back into a Django model instance.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 1: Setting Up Your Django&amp;nbsp;Project&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Before we dive into serializers, let&amp;rsquo;s ensure that your Django project is set up correctly.&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Install Django and Django REST Framework&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;cmake&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;pip install django djangorestframework&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Create a Django Project&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;bash&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;django-admin startproject myproject cd myproject&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Create a Django App&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;python manage.py startapp myapp&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. Add &lt;/b&gt;&lt;b&gt;rest_framework&lt;/b&gt;&lt;b&gt; and &lt;/b&gt;&lt;b&gt;myapp&lt;/b&gt;&lt;b&gt; to &lt;/b&gt;&lt;b&gt;INSTALLED_APPS&lt;/b&gt;:&lt;br /&gt;In myproject/settings.py, add:&lt;/p&gt;
&lt;pre class=&quot;ini&quot; data-code-block-lang=&quot;ini&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;INSTALLED_APPS = [ &amp;hellip; 'rest_framework', 'myapp', ]&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 2: Creating a&amp;nbsp;Model&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s create a simple Book model in myapp/models.py:&lt;/p&gt;
&lt;pre class=&quot;reasonml&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;from django.db import models
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    isbn = models.CharField(max_length=13, unique=True)
    def __str__(self):
        return self.title&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;5. Run Migrations&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;python manage.py makemigrations 
python manage.py migrate&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 3: Creating a Serializer&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Serializers are defined in a serializers.py file within your app. Let's create a serializer for the Book model.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In myapp/serializers.py, create a BookSerializer:&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;kotlin&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date', 'isbn']&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Key Points About Serializers:&lt;/h4&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;ModelSerializer&lt;/b&gt;: This is a shortcut for creating serializers that map closely to Django models. It automatically generates fields based on the model and provides default implementations for creating and updating instances.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;fields&lt;/b&gt;: This attribute specifies which fields from the model should be included in the serialized output. You can also use __all__ to include all fields.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;read_only_fields&lt;/b&gt;: You can specify fields that should be read-only (e.g., id).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;extra_kwargs&lt;/b&gt;: This allows you to specify additional options for fields, such as making a field write-only or adding validation rules.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 4: Creating&amp;nbsp;Views&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now that we have a serializer, let&amp;rsquo;s create views to handle API requests. We&amp;rsquo;ll use DRF&amp;rsquo;s generic views to simplify the process.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In myapp/views.py:&lt;/p&gt;
&lt;pre class=&quot;haskell&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookListCreateView(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
class BookDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Key Points About&amp;nbsp;Views:&lt;/h4&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;ListCreateAPIView&lt;/b&gt;: This view handles both listing all instances of a model and creating new instances.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;RetrieveUpdateDestroyAPIView&lt;/b&gt;: This view handles retrieving, updating, and deleting a single instance of a model.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;queryset&lt;/b&gt;: This specifies the set of objects that the view will operate on.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;serializer_class&lt;/b&gt;: This specifies the serializer to use for converting the model instances to JSON and vice versa.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 5: Defining&amp;nbsp;URLs&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Next, we need to define the URLs for our API. In myapp/urls.py:&lt;/p&gt;
&lt;pre class=&quot;pgsql&quot; data-code-block-lang=&quot;javascript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;from django.urls import path
from .views import BookListCreateView, BookDetailView
urlpatterns = [
    path('books/', BookListCreateView.as_view(), name='book-list-create'),
    path('books/&amp;lt;int:pk&amp;gt;/', BookDetailView.as_view(), name='book-detail'),
]&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Then, include these URLs in the project&amp;rsquo;s urls.py (in myproject/urls.py):&lt;/p&gt;
&lt;pre class=&quot;pgsql&quot; data-code-block-lang=&quot;javascript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 6: Testing the&amp;nbsp;API&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Run the Development Server&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;ython manage.py runserver&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Access the API&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Go to http://127.0.0.1:8000/api/books/ to see the list of books or create a new one.&lt;/li&gt;
&lt;li&gt;Go to http://127.0.0.1:8000/api/books/1/ to view, update, or delete a specific book.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Add Data via Django Admin&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Register the Book model in myapp/admin.py:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;pgsql&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;from django.contrib import admin
from .models import Book

admin.site.register(Book)&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Create a superuser:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;python manage.py createsuperuser&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Log in to the admin panel (http://127.0.0.1:8000/admin/) and add some books.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 7: Testing with Postman or&amp;nbsp;Curl&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can use tools like Postman or curl to test your API endpoints.&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Create a Book&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;curl -X POST -H &amp;ldquo;Content-Type: application/json&amp;rdquo; -d &amp;lsquo;{&amp;ldquo;title&amp;rdquo;: &amp;ldquo;1984&amp;rdquo;, &amp;ldquo;author&amp;rdquo;: &amp;ldquo;George Orwell&amp;rdquo;, &amp;ldquo;published_date&amp;rdquo;: &amp;ldquo;1949&amp;ndash;06&amp;ndash;08&amp;rdquo;, &amp;ldquo;isbn&amp;rdquo;: &amp;ldquo;9780451524935&amp;rdquo;}&amp;rsquo; &lt;a href=&quot;http://127.0.0.1:8000/api/books/&quot; data-href=&quot;http://127.0.0.1:8000/api/books/&quot;&gt;http://127.0.0.1:8000/api/books/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;scilab&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;curl -X POST -H &quot;Content-Type: application/json&quot; -d '{&quot;title&quot;: &quot;1984&quot;, &quot;author&quot;: &quot;George Orwell&quot;, &quot;published_date&quot;: &quot;1949-06-08&quot;, &quot;isbn&quot;: &quot;9780451524935&quot;}' http://127.0.0.1:8000/api/books/&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Get All Books&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;awk&quot; data-code-block-lang=&quot;ruby&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;curl http://127.0.0.1:8000/api/books/&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Get a Specific Book&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;awk&quot; data-code-block-lang=&quot;ruby&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;curl http://127.0.0.1:8000/api/books/1/&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. Update a Book&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;scilab&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;curl -X PUT -H &quot;Content-Type: application/json&quot; -d '{&quot;title&quot;: &quot;1984&quot;, &quot;author&quot;: &quot;George Orwell&quot;, &quot;published_date&quot;: &quot;1949&amp;ndash;06&amp;ndash;08&quot;, &quot;isbn&quot;: &quot;9780451524935&quot;}' http://127.0.0.1:8000/api/books/1/&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;5. Delete a Book&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;awk&quot; data-code-block-lang=&quot;ruby&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;curl -X DELETE http://127.0.0.1:8000/api/books/1/&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Summary&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this lesson, we:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Created a Django model (Book).&lt;/li&gt;
&lt;li&gt;Created a serializer (BookSerializer) to convert the model into JSON.&lt;/li&gt;
&lt;li&gt;Created views to handle API requests (BookListCreateView and BookDetailView).&lt;/li&gt;
&lt;li&gt;Defined URLs for the API.&lt;/li&gt;
&lt;li&gt;Tested the API using the Django development server and tools like Postman or curl.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;By following these steps, you now have a basic understanding of how serializers work in Django REST Framework and how they can be used to build RESTful APIs. In the next lesson, we will explore more advanced features of serializers, such as custom validation and nested serializers.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Django Essentials</category>
      <category>api development</category>
      <category>api 개발</category>
      <category>backend development</category>
      <category>Django REST Framework</category>
      <category>model-to-json</category>
      <category>Serializers</category>
      <category>모델-to-json</category>
      <category>백엔드 개발</category>
      <category>시리얼라이저</category>
      <category>장고 rest 프레임워크</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/35</guid>
      <comments>https://codeaddict.tistory.com/entry/Django-REST-Framework004-erializers-and-Model-to-JSON-Conversion#entry35comment</comments>
      <pubDate>Thu, 6 Feb 2025 23:51:33 +0900</pubDate>
    </item>
    <item>
      <title>Django REST Framework_003: Visualizing Django Models with django-extensions</title>
      <link>https://codeaddict.tistory.com/entry/Django-REST-Framework003-Visualizing-Django-Models-with-django-extensions</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In Django projects, understanding the relationships between your models is essential for designing and maintaining your application. While Django&amp;rsquo;s ORM makes it easy to define models and their relationships, visualizing these relationships can help you better understand your database schema.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this lesson, we will:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Use django-extensions to generate a&amp;nbsp;.dot file for your Django models.&lt;/li&gt;
&lt;li&gt;Visualize the&amp;nbsp;.dot file using the &lt;b&gt;Graphviz Online Editor&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;Automatically generate a diagram from the&amp;nbsp;.dot file.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Why Use Graphviz&amp;nbsp;Online?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Graphviz Online (&lt;a href=&quot;https://dreampuf.github.io/GraphvizOnline&quot;&gt;https://dreampuf.github.io/GraphvizOnline&lt;/a&gt;) is a web-based tool that allows you to visualize&amp;nbsp;.dot files without installing any additional software. It&amp;rsquo;s perfect for quickly generating and sharing diagrams of your Django models.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 1: Install Required&amp;nbsp;Packages&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To generate a&amp;nbsp;.dot file, you&amp;rsquo;ll need the django-extensions library.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Install django-extensions&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Run the following command in your terminal:&lt;/p&gt;
&lt;pre class=&quot;cmake&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;pip install django-extensions&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 2: Add django-extensions to Your Django&amp;nbsp;Project&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Open your Django project&amp;rsquo;s settings.py file.&lt;/li&gt;
&lt;li&gt;Add 'django_extensions' to the INSTALLED_APPS list:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;ini&quot; data-code-block-lang=&quot;ini&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;INSTALLED_APPS = [ &amp;hellip; 'django_extensions', &amp;hellip; ]&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 3: Generate the&amp;nbsp;.dot&amp;nbsp;File&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now that django-extensions is installed, you can use the graph_models command to generate a&amp;nbsp;.dot file for your Django models.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Generate a&amp;nbsp;.dot File for All&amp;nbsp;Models&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To generate a&amp;nbsp;.dot file for all models in your project, run:&lt;/p&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;python manage.py graph_models -a &amp;gt; models.dot&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;-a: Include all models in your project.&lt;/li&gt;
&lt;li&gt;&amp;gt; models.dot: Save the output to a file named models.dot.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Generate a&amp;nbsp;.dot File for a Specific&amp;nbsp;App&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;If you only want to generate a&amp;nbsp;.dot file for a specific app (e.g., api), run:&lt;/p&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;python manage.py graph_models api &amp;gt; api_models.dot&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 4: Visualize the&amp;nbsp;.dot File Using Graphviz&amp;nbsp;Online&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Open the &lt;b&gt;Graphviz Online Editor&lt;/b&gt; in your browser: &lt;a href=&quot;https://dreampuf.github.io/GraphvizOnline&quot;&gt;https://dreampuf.github.io/GraphvizOnline&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Open the&amp;nbsp;.dot file you generated (e.g., models.dot) in a text editor (like Notepad, VS Code, or any other editor).&lt;/li&gt;
&lt;li&gt;Copy the entire content of the&amp;nbsp;.dot file.&lt;/li&gt;
&lt;li&gt;Paste the content into the &lt;b&gt;Graphviz Online Editor&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;The diagram will be automatically generated and displayed in the editor.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 5: Interpret the&amp;nbsp;Diagram&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The generated diagram will show:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Models&lt;/b&gt;: Each box represents a Django model.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Fields&lt;/b&gt;: The fields of each model are listed inside the box.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Relationships&lt;/b&gt;: Arrows between boxes represent relationships like ForeignKey, OneToOneField, and ManyToManyField.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;For example:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;A solid arrow with a single head represents a ForeignKey relationship.&lt;/li&gt;
&lt;li&gt;A solid arrow with two heads represents a ManyToManyField relationship.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 6: Customize the Diagram (Optional)&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;If you want to customize the diagram, you can edit the&amp;nbsp;.dot file before pasting it into the Graphviz Online Editor. For example:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Change Colors&lt;/b&gt;: Add color attributes to the nodes (models) or edges (relationships).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Group Models&lt;/b&gt;: Use subgraphs to group models by app or functionality.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s an example of a customized&amp;nbsp;.dot file:&lt;/p&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;digraph G {
    node [shape=box, style=filled, color=lightblue];
    edge [color=gray];

    User [label=&quot;User\nusername\nemail&quot;];
    Profile [label=&quot;Profile\nbio\nimage&quot;];
    Post [label=&quot;Post\ntitle\ncontent&quot;];

    User -&amp;gt; Profile [label=&quot;OneToOne&quot;];
    User -&amp;gt; Post [label=&quot;ForeignKey&quot;];
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Common Issues and Troubleshooting&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;No Models Found&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Make sure the app name you provided in the command is correct.&lt;/li&gt;
&lt;li&gt;Ensure the app is included in INSTALLED_APPS.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Graphviz Online Not Rendering&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Check the&amp;nbsp;.dot file for syntax errors.&lt;/li&gt;
&lt;li&gt;Ensure the file is properly formatted and contains valid Graphviz code.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Output File Not Generated&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Check the command syntax and ensure the output file path is valid.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Django Essentials</category>
      <category>django</category>
      <category>Django REST Framework</category>
      <category>DRF</category>
      <category>장고</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/34</guid>
      <comments>https://codeaddict.tistory.com/entry/Django-REST-Framework003-Visualizing-Django-Models-with-django-extensions#entry34comment</comments>
      <pubDate>Sat, 1 Feb 2025 23:02:15 +0900</pubDate>
    </item>
    <item>
      <title>cpp_011: Understanding the sizeof Operator in&amp;nbsp;C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp011-Understanding-the-sizeof-Operator-in-C</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this lesson, we&amp;rsquo;ll explore the sizeof operator in C++. This operator is used to determine the size (in bytes) of a variable, data type, or entire array. It's important to understand that sizeof does &lt;b&gt;not directly give the number of elements in an array&lt;/b&gt; but rather the total memory size. To calculate the number of elements, you need to divide the total size of the array by the size of a single element. Let&amp;rsquo;s dive into the syntax and an example to understand how it works.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. Syntax of sizeof&amp;nbsp;Operator&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The sizeof operator can be used in two ways:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;For Variables or Data Types&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;lisp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;sizeof(variableName);
sizeof(dataType);&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. For Arrays&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;lisp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;sizeof(arrayName) / sizeof(arrayName[0]);&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;sizeof(arrayName): Returns the total size of the array in bytes.&lt;/li&gt;
&lt;li&gt;sizeof(arrayName[0]): Returns the size of a single element in the array.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Example: Using sizeof with&amp;nbsp;Arrays&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s write a program to calculate the size of an array and the number of elements it contains.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem Statement:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Write a C++ program to:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Declare an array of integers.&lt;/li&gt;
&lt;li&gt;Use the sizeof operator to determine the total size of the array and the size of a single element.&lt;/li&gt;
&lt;li&gt;Calculate and display the number of elements in the array.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Solution Code&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;csharp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    // Calculate the total size of the array in bytes
    int totalSize = sizeof(numbers);
    // Calculate the size of a single element in bytes
    int elementSize = sizeof(numbers[0]);
    // Calculate the number of elements in the array
    int numElements = totalSize / elementSize;
    cout &amp;lt;&amp;lt; &quot;Total size of the array: &quot; &amp;lt;&amp;lt; totalSize &amp;lt;&amp;lt; &quot; bytes&quot; &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Size of a single element: &quot; &amp;lt;&amp;lt; elementSize &amp;lt;&amp;lt; &quot; bytes&quot; &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Number of elements in the array: &quot; &amp;lt;&amp;lt; numElements &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Total Size of the Array&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;sizeof(numbers) returns the total size of the array in bytes. For example, if the array has 5 integers and each integer occupies 4 bytes, the total size will be 20 bytes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Size of a Single Element&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;sizeof(numbers[0]) returns the size of the first element in the array. For an int, this is typically 4 bytes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Number of Elements&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Dividing the total size of the array by the size of a single element gives the number of elements in the array.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output&lt;/h3&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Total size of the array: 20 bytes  
Size of a single element: 4 bytes  
Number of elements in the array: 5&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Takeaway&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The sizeof operator is a powerful tool for understanding memory allocation and calculating the size of arrays or variables. Use it to make your programs more dynamic and efficient!&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>array size</category>
      <category>c++ 메모리</category>
      <category>sizeof operator</category>
      <category>sizeof 연산자</category>
      <category>배열 크기</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/33</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp011-Understanding-the-sizeof-Operator-in-C#entry33comment</comments>
      <pubDate>Sat, 1 Feb 2025 15:07:12 +0900</pubDate>
    </item>
    <item>
      <title>CSS_004_Grouping Selectors in&amp;nbsp;CSS</title>
      <link>https://codeaddict.tistory.com/entry/CSS004Grouping-Selectors-in-CSS</link>
      <description>&lt;p data-ke-size=&quot;size16&quot;&gt;In this blog post, we&amp;rsquo;ll explore &lt;b&gt;grouping in CSS&lt;/b&gt;, a powerful technique to apply the same styles to multiple selectors like headers, classes, and IDs. Grouping helps reduce redundancy and keeps your CSS clean. We&amp;rsquo;ll also learn how to style one of the grouped elements differently by creating a new class or ID.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;HTML Structure&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s the HTML structure for this lesson. Don&amp;rsquo;t forget to link the CSS file!&lt;/p&gt;
&lt;pre class=&quot;xml&quot; data-code-block-lang=&quot;xml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Grouping in CSS&amp;lt;/title&amp;gt;
  &amp;lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&amp;gt; &amp;lt;!-- Link to your CSS file --&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;h1&amp;gt;Heading 1&amp;lt;/h1&amp;gt;
  &amp;lt;h2&amp;gt;Heading 2&amp;lt;/h2&amp;gt;
  &amp;lt;p class=&quot;text&quot;&amp;gt;This is a paragraph.&amp;lt;/p&amp;gt;
  &amp;lt;p id=&quot;special-text&quot;&amp;gt;This is a special paragraph.&amp;lt;/p&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Grouping Selectors&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can group selectors by separating them with commas. For example, in your styles.css file:&lt;/p&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;h1, h2, .text {
  color: blue;
  font-size: 18px;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This applies the same styles to &amp;lt;h1&amp;gt;, &amp;lt;h2&amp;gt;, and elements with the class&amp;nbsp;.text.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Styling One Element Differently&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To style the #special-text paragraph differently, create a new rule in your CSS file:&lt;/p&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#special-text {
  color: red;
  font-weight: bold;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, the special paragraph stands out while the rest share the grouped styles.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Final Output&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s how your styles.css file should look:&lt;/p&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;h1, h2, .text {
  color: blue;
  font-size: 18px;
}

#special-text {
  color: red;
  font-weight: bold;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Grouping selectors saves time and makes your CSS more efficient. Try it out in your next project!&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;</description>
      <category>Web Development Basics (CSS, JavaScript,</category>
      <category>css grouping</category>
      <category>css selectors</category>
      <category>css 그룹화</category>
      <category>CSS 선택자</category>
      <category>web development basics</category>
      <category>웹 개발 기초</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/32</guid>
      <comments>https://codeaddict.tistory.com/entry/CSS004Grouping-Selectors-in-CSS#entry32comment</comments>
      <pubDate>Sat, 1 Feb 2025 13:52:54 +0900</pubDate>
    </item>
    <item>
      <title>socket_003:Sending and Receiving Video over&amp;nbsp;Sockets</title>
      <link>https://codeaddict.tistory.com/entry/socket002Sending-and-Receiving-Video-over-Sockets</link>
      <description>&lt;h4 data-ke-size=&quot;size20&quot;&gt;In this tutorial, we will explore how to send and receive video frames over a network using Python sockets. We will break down both the server and client code to understand how video data is transmitted and displayed in real-time.&lt;/h4&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Overview&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Server Code&lt;/b&gt;: The server listens for incoming connections, receives video frames from the client, and displays them.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Client Code&lt;/b&gt;: The client reads video frames from a video file, sends them to the server, and displays them locally.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Server Code Breakdown&lt;/h3&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import socket
import cv2
import pickle
import struct

def recv_exact(sock, size):
    &quot;&quot;&quot;Receive exactly `size` bytes from the socket.&quot;&quot;&quot;
    data = b&quot;&quot;
    while len(data) &amp;lt; size:
        packet = sock.recv(size - len(data))
        if not packet:
            return None
        data += packet
    return data

# Create a TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
print(&quot;Waiting for client connection...&quot;)

client_socket, addr = server_socket.accept()
print(&quot;Connected to:&quot;, addr)

try:
    while True:
        # Receive the frame size (4 bytes)
        packed_size = client_socket.recv(4)
        if not packed_size:
            break
        frame_size = struct.unpack(&quot;I&quot;, packed_size)[0]

        # Receive the complete frame data
        frame_data = recv_exact(client_socket, frame_size)
        if frame_data is None:
            break

        # Deserialize and decode the frame
        frame = cv2.imdecode(pickle.loads(frame_data), cv2.IMREAD_COLOR)

        # Display the frame
        cv2.imshow(&quot;Server Camera&quot;, frame)

        if cv2.waitKey(1) &amp;amp; 0xFF == ord('q'):
            break

except Exception as e:
    print(&quot;Error:&quot;, e)

finally:
    cv2.destroyAllWindows()
    client_socket.close()
    server_socket.close()
    print(&quot;Connection closed.&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Key Functions and Concepts in Server&amp;nbsp;Code&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;recv_exact(sock, size)&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;This function ensures that exactly size bytes are received from the socket. It is necessary because recv() may not always return the exact number of bytes requested.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Parameters&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;sock: The socket object.&lt;/li&gt;
&lt;li&gt;size: The number of bytes to receive.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. socket.socket(socket.AF_INET, socket.SOCK_STREAM)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Creates a TCP socket.&lt;/li&gt;
&lt;li&gt;AF_INET specifies the address family (IPv4).&lt;/li&gt;
&lt;li&gt;SOCK_STREAM specifies the socket type (TCP).&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. server_socket.bind(('localhost', 12345))&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Binds the socket to the localhost on port 12345.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. server_socket.listen(1)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Listens for incoming connections. The argument 1 specifies the maximum number of pending connections.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;5. client_socket, addr = server_socket.accept()&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Accepts a connection from a client. Returns a new socket object (client_socket) and the address of the client (addr).&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;6. struct.unpack(&quot;I&quot;, packed_size)[0]&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Unpacks the frame size from the received 4-byte data. &quot;I&quot; specifies an unsigned integer.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;7. cv2.imdecode(pickle.loads(frame_data), cv2.IMREAD_COLOR)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Deserializes the frame data using pickle.loads() and decodes it into an image using cv2.imdecode().&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;8. cv2.imshow(&quot;Server Camera&quot;, frame)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Displays the received frame in a window titled &amp;ldquo;Server Camera&amp;rdquo;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;9. cv2.waitKey(1)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Waits for 1 millisecond for a key event. If the &amp;lsquo;q&amp;rsquo; key is pressed, the loop breaks.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Client Code Breakdown&lt;/h3&gt;
&lt;pre class=&quot;xl&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import socket
import cv2
import pickle
import struct
import time

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))

video_path = 'mix.mp4'  # Replace with your video file path
cap = cv2.VideoCapture(video_path)

fps = cap.get(cv2.CAP_PROP_FPS)
print(f&quot;Video FPS: {fps}&quot;)

try:
    while True:
        start_time = time.time()
        ret, frame = cap.read()
        if not ret:
            break

        # Resize and compress the frame
        frame = cv2.resize(frame, (640, 480))
        ret, buffer = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 80])
        data = pickle.dumps(buffer)
        message_size = struct.pack(&quot;I&quot;, len(data))
        client_socket.sendall(message_size + data)

        cv2.imshow(&quot;Client Camera&quot;, frame)
        if cv2.waitKey(1) &amp;amp; 0xFF == ord('q'):
            break

        time_to_sleep = max(0, (1 / fps) - (time.time() - start_time))
        time.sleep(time_to_sleep)

except KeyboardInterrupt:
    print(&quot;Client stopped.&quot;)

finally:
    cap.release()
    client_socket.close()
    cv2.destroyAllWindows()&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Key Functions and Concepts in Client&amp;nbsp;Code&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;client_socket.connect(('localhost', 12345))&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Connects the client socket to the server at localhost on port 12345.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. cv2.VideoCapture(video_path)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Opens the video file specified by video_path.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. cap.get(cv2.CAP_PROP_FPS)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Retrieves the frames per second (FPS) of the video.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. cap.read()&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Reads the next frame from the video. Returns ret (a boolean indicating success) and frame (the actual frame).&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;5. cv2.resize(frame, (640, 480))&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Resizes the frame to 640x480 pixels.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;6. cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 80])&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Encodes the frame as a JPEG image with 80% quality.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;7. pickle.dumps(buffer)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Serializes the encoded frame data into a byte stream.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;8. struct.pack(&quot;I&quot;, len(data))&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Packs the length of the serialized frame data into a 4-byte unsigned integer.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;9. client_socket.sendall(message_size + data)&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Sends the frame size followed by the frame data to the server.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This tutorial demonstrated how to send and receive video frames over a network using Python sockets. The server receives and displays the frames, while the client reads frames from a video file, sends them to the server, and displays them locally. By understanding the key functions and concepts, you can build more complex video streaming applications.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;</description>
      <category>Backend Technologies</category>
      <category>backend</category>
      <category>OpenCV</category>
      <category>socket</category>
      <category>파이썬네트워킹</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/31</guid>
      <comments>https://codeaddict.tistory.com/entry/socket002Sending-and-Receiving-Video-over-Sockets#entry31comment</comments>
      <pubDate>Thu, 30 Jan 2025 21:22:01 +0900</pubDate>
    </item>
    <item>
      <title>socket_002: Real-Time Camera Streaming with Sockets</title>
      <link>https://codeaddict.tistory.com/entry/socket002-Real-Time-Camera-Streaming-with-Sockets</link>
      <description>&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this tutorial, we&amp;rsquo;ll create a server that captures video from a webcam and streams it to a client over a network. The client will receive the video frames and display them in real-time.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Prerequisites&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Install the required libraries:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;cmake&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;pip install opencv-python&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;2. Ensure you have a webcam connected to your machine.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash;&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;How It&amp;nbsp;Works&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Server Side&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Capture video frames from the webcam using OpenCV.&lt;/li&gt;
&lt;li&gt;Encode the frames into a byte stream.&lt;/li&gt;
&lt;li&gt;Send the encoded frames to the client over a socket.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Client Side&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Receive the encoded frames from the server.&lt;/li&gt;
&lt;li&gt;Decode the frames and display them using OpenCV.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash;&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 1: Create the Camera Streaming Server&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Save the following code in a file named camera_server.py:&lt;/p&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import socket
import cv2
import pickle
import struct

# Create a TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to an IP address and port
server_address = ('localhost', 12345)
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(1)
print(&quot;Camera server is listening on port 12345...&quot;)

# Accept a connection from a client
client_socket, client_address = server_socket.accept()
print(f&quot;Connection established with {client_address}&quot;)

# Set a timeout for the client socket (e.g., 5 seconds)
client_socket.settimeout(5.0)

# Initialize a buffer to store the incoming data
data_buffer = b&quot;&quot;
# Size of the payload (4 bytes for the length of the frame)
payload_size = struct.calcsize(&quot;L&quot;)

try:
    while True:
        try:
            # Receive the frame size from the client
            while len(data_buffer) &amp;lt; payload_size:
                packet = client_socket.recv(4096)
                if not packet:  # Client disconnected
                    print(&quot;Client disconnected.&quot;)
                    break
                data_buffer += packet

            if not data_buffer:
                break  # Exit if client disconnected

            # Extract the frame size from the buffer
            packed_msg_size = data_buffer[:payload_size]
            data_buffer = data_buffer[payload_size:]
            msg_size = struct.unpack(&quot;L&quot;, packed_msg_size)[0]

            # Receive the frame data from the client
            while len(data_buffer) &amp;lt; msg_size:
                packet = client_socket.recv(4096)
                if not packet:  # Client disconnected
                    print(&quot;Client disconnected.&quot;)
                    break
                data_buffer += packet

            if not data_buffer:
                break  # Exit if client disconnected

            # Extract the frame from the buffer
            frame_data = data_buffer[:msg_size]
            data_buffer = data_buffer[msg_size:]

            # Deserialize the frame
            frame = pickle.loads(frame_data)

            # Overlay text on the frame to indicate it's from the server
            cv2.putText(frame, &quot;From Server&quot;, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

            # Display the frame in a window
            cv2.imshow(&quot;Server Camera&quot;, frame)
            if cv2.waitKey(1) &amp;amp; 0xFF == ord('q'):
                break

        except socket.timeout:
            print(&quot;No data received from client. Closing connection.&quot;)
            break

except KeyboardInterrupt:
    print(&quot;Server stopped.&quot;)

finally:
    # Release resources
    cv2.destroyAllWindows()
    client_socket.close()
    server_socket.close()&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 2: Create the Camera Streaming Client&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Save the following code in a file named camera_client.py:&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import socket
import cv2
import pickle
import struct

# Create a TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server
server_address = ('localhost', 12345)
client_socket.connect(server_address)

# Open the webcam
cap = cv2.VideoCapture(0)

try:
    while True:
        # Capture a frame from the webcam
        ret, frame = cap.read()
        if not ret:
            break

        # Serialize the frame into a byte stream
        data = pickle.dumps(frame)
        # Pack the length of the data into a 4-byte header
        message_size = struct.pack(&quot;L&quot;, len(data))

        # Send the frame to the server
        client_socket.sendall(message_size + data)

        # Display the original frame in a window (optional)
        cv2.imshow(&quot;Client Camera&quot;, frame)
        if cv2.waitKey(1) &amp;amp; 0xFF == ord('q'):
            break

except KeyboardInterrupt:
    print(&quot;Client stopped.&quot;)

finally:
    # Release resources
    cap.release()
    client_socket.close()
    cv2.destroyAllWindows()&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 3: Run the&amp;nbsp;Code&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Open two terminal windows&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;One for the server.&lt;/li&gt;
&lt;li&gt;One for the client.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Run the server&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;In the first terminal, navigate to the directory where camera_server.py is saved.&lt;/li&gt;
&lt;li&gt;Run the server using the following command:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;python camera_server.py&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The server will start and display:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;csharp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Camera server is listening on port 12345&amp;hellip;&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Run the client&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;In the second terminal, navigate to the directory where camera_client.py is saved.&lt;/li&gt;
&lt;li&gt;Run the client using the following command:&lt;/li&gt;
&lt;li&gt;python camera_client.py&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;python camera_client.py&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;A window will open displaying the live camera stream from the server.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. Stop the streaming&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Press q in the client window to stop the stream and close the window.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;How It&amp;nbsp;Works&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;The server captures video frames from the webcam using OpenCV.&lt;/li&gt;
&lt;li&gt;Each frame is serialized into a byte stream using pickle.&lt;/li&gt;
&lt;li&gt;The server sends the frame size (as a 4-byte header) followed by the frame data to the client.&lt;/li&gt;
&lt;li&gt;The client receives the frame size and data, deserializes the frame, and displays it using OpenCV.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Takeaways&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Sockets can be used to stream real-time data, such as video, between a server and a client.&lt;/li&gt;
&lt;li&gt;OpenCV is a powerful library for capturing and processing video frames.&lt;/li&gt;
&lt;li&gt;Serialization (using pickle) is necessary to send complex data (like images) over sockets.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Backend Technologies</category>
      <category>camerastreaming</category>
      <category>OpenCV</category>
      <category>socket</category>
      <category>소켓 프로그래밍</category>
      <category>카메라스트리밍</category>
      <category>파이썬네트워킹</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/30</guid>
      <comments>https://codeaddict.tistory.com/entry/socket002-Real-Time-Camera-Streaming-with-Sockets#entry30comment</comments>
      <pubDate>Thu, 30 Jan 2025 12:23:42 +0900</pubDate>
    </item>
    <item>
      <title>socket_001: Introduction to Sockets in&amp;nbsp;Python</title>
      <link>https://codeaddict.tistory.com/entry/socket001-Introduction-to-Sockets-in-Python</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Sockets are the backbone of network communication. They allow programs to send and receive data over a network, enabling applications to communicate with each other. Whether you&amp;rsquo;re building a chat application, a file transfer system, or a web server, understanding sockets is essential.&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this tutorial, we&amp;rsquo;ll cover the basics of sockets, including what they are, how they work, and how to create a simple client-server communication using Python.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;What is a&amp;nbsp;Socket?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A socket is an endpoint for communication between two machines. It combines an IP address and a port number to uniquely identify a connection. Sockets can be used for various types of communication, such as TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;TCP&lt;/b&gt;: Reliable, connection-oriented communication. Data is delivered in order and without errors.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;UDP&lt;/b&gt;: Unreliable, connectionless communication. Data is sent without guaranteeing delivery or order.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this tutorial, we&amp;rsquo;ll focus on &lt;b&gt;TCP sockets&lt;/b&gt;, as they are the most commonly used.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Basic Socket&amp;nbsp;Workflow&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Server Side&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Create a socket.&lt;/li&gt;
&lt;li&gt;Bind the socket to an IP address and port.&lt;/li&gt;
&lt;li&gt;Listen for incoming connections.&lt;/li&gt;
&lt;li&gt;Accept a connection from a client.&lt;/li&gt;
&lt;li&gt;Send and receive data.&lt;/li&gt;
&lt;/ul&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Client Side&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Create a socket.&lt;/li&gt;
&lt;li&gt;Connect to the server&amp;rsquo;s IP address and port.&lt;/li&gt;
&lt;li&gt;Send and receive data.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Basic Socket Commands and&amp;nbsp;Syntax&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here are the fundamental socket commands in Python:&lt;/p&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;perl&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;| Command/Syntax                | Description                                                                 |
|-------------------------------|-----------------------------------------------------------------------------|
| `socket.socket()`             | Creates a new socket.                                                       |
| `socket.bind((host, port))`   | Binds the socket to a specific IP address and port.                         |
| `socket.listen()`             | Puts the socket in listening mode (for servers).                            |
| `socket.accept()`             | Accepts an incoming connection (returns a new socket and client address).   |
| `socket.connect((host, port))`| Connects to a remote socket (for clients).                              |
| `socket.send(data)`           | Sends data to the connected socket.                                         |
| `socket.recv(buffer_size)`    | Receives data from the socket (up to `buffer_size` bytes).                  |
| `socket.close()`              | Closes the socket.                                                          |&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Creating a Simple TCP Server and&amp;nbsp;Client&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s create a basic TCP server and client to demonstrate how sockets work. &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash; &amp;mdash;&amp;nbsp;&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Step 1: Create the TCP&amp;nbsp;Server&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The server will listen for incoming connections and respond to messages from the client.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Save the following code in a file named server.py:&lt;/p&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import socket

# Create a TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to an IP address and port
server_address = ('localhost', 12345)
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(1)
print(&quot;Server is listening on port 12345...&quot;)

# Accept a connection
client_socket, client_address = server_socket.accept()
print(f&quot;Connection established with {client_address}&quot;)

# Receive data from the client
data = client_socket.recv(1024).decode()
print(f&quot;Received: {data}&quot;)

# Send a response to the client
response = &quot;Hello from the server!&quot;
client_socket.send(response.encode())

# Close the sockets
client_socket.close()
server_socket.close()&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Step 2: Create the TCP&amp;nbsp;Client&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The client will connect to the server, send a message, and receive a response.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Save the following code in a file named client.py:&lt;/p&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;import socket

# Create a TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server
server_address = ('localhost', 12345)
client_socket.connect(server_address)

# Send data to the server
message = &quot;Hello from the client!&quot;
client_socket.send(message.encode())

# Receive a response from the server
data = client_socket.recv(1024).decode()
print(f&quot;Received: {data}&quot;)

# Close the socket
client_socket.close()&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Step 3: Run the&amp;nbsp;Code&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Follow these steps to run the server and client:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Open two terminal windows&lt;/b&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;One for the server.&lt;/li&gt;
&lt;li&gt;One for the client.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Run the server&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;In the first terminal, navigate to the directory where server.py is saved.&lt;/li&gt;
&lt;li&gt;Run the server using the following command:&lt;/li&gt;
&lt;li&gt;python server.py&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;python server.py&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The server will start and display:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Server is listening on port 12345&amp;hellip;&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. Run the client&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;In the second terminal, navigate to the directory where client.py is saved.&lt;/li&gt;
&lt;li&gt;Run the client using the following command&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;python client.py&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The client will send a message to the server and display the server&amp;rsquo;s response:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Received: Hello from the server&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;4. Observe the server output&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;After the client runs, the server terminal will display:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Connection established with ('127.0.0.1', &amp;lt;client_port&amp;gt;) Received: Hello from the client!&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;How It&amp;nbsp;Works&lt;/h3&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;The server creates a socket, binds it to localhost:12345, and starts listening for connections.&lt;/li&gt;
&lt;li&gt;The client creates a socket and connects to the server at localhost:12345.&lt;/li&gt;
&lt;li&gt;The client sends a message (&quot;Hello from the client!&quot;) to the server.&lt;/li&gt;
&lt;li&gt;The server receives the message, prints it, and sends a response (&quot;Hello from the server!&quot;) back to the client.&lt;/li&gt;
&lt;li&gt;The client receives the response and prints it.&lt;/li&gt;
&lt;li&gt;Both the client and server close their sockets.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Server Output:&lt;/h4&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;vbnet&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Server is listening on port 12345...
Connection established with ('127.0.0.1', &amp;lt;client_port&amp;gt;)
Received: Hello from the client!&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Client Output:&lt;/h4&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Received: Hello from the server!&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Takeaways&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Sockets are the foundation of network communication.&lt;/li&gt;
&lt;li&gt;A server listens for incoming connections, while a client initiates the connection.&lt;/li&gt;
&lt;li&gt;The socket module in Python provides all the tools you need to create and manage sockets.&lt;/li&gt;
&lt;li&gt;Always close sockets after use to free up resources.&lt;/li&gt;
&lt;li&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Backend Technologies</category>
      <category>Network</category>
      <category>socket</category>
      <category>tcp</category>
      <category>tcp통신</category>
      <category>네트워크 소켓</category>
      <category>소켓</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/29</guid>
      <comments>https://codeaddict.tistory.com/entry/socket001-Introduction-to-Sockets-in-Python#entry29comment</comments>
      <pubDate>Thu, 30 Jan 2025 12:13:45 +0900</pubDate>
    </item>
    <item>
      <title>Django REST Framework_001: Using a Custom User&amp;nbsp;Model</title>
      <link>https://codeaddict.tistory.com/entry/Django-REST-Framework001-Using-a-Custom-User-Model</link>
      <description>&lt;p data-ke-size=&quot;size16&quot;&gt;In Django projects, working with users is a fundamental part of many applications. By default, Django provides the auth.User model, which includes basic user fields like username, email, password, etc. While sufficient for many scenarios, this default model may not always fit your application&amp;rsquo;s needs. To address this, Django allows you to define your own custom user model.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this lesson, we will:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Learn how to define a custom user model.&lt;/li&gt;
&lt;li&gt;Understand what the AUTH_USER_MODEL setting does and why it&amp;rsquo;s essential.&lt;/li&gt;
&lt;li&gt;Discuss common issues when AUTH_USER_MODEL is not properly configured and how to resolve them.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Why Use a Custom User&amp;nbsp;Model?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Sometimes, the default auth.User model may not meet the requirements of your application. For example, you might want to:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Add fields like phone_number, profile_picture, or date_of_birth.&lt;/li&gt;
&lt;li&gt;Remove unnecessary fields that your application does not use.&lt;/li&gt;
&lt;li&gt;Extend the default user authentication functionality.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Using a custom user model allows for these customizations while maintaining compatibility with Django&amp;rsquo;s built-in authentication system.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Steps to Create and Use a Custom User&amp;nbsp;Model&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Step 1: Create a New Django&amp;nbsp;Project&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Run the following commands to set up a Django project and app:&lt;/p&gt;
&lt;pre class=&quot;nsis&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;django-admin startproject custom_user_project
cd custom_user_project
django-admin startapp api&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This creates the project custom_user_project and the app api.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Step 2: Define the Custom User&amp;nbsp;Model&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In the api app, define a custom user model in models.py. To create a custom user model, Django provides the AbstractUser class, which already includes the basic fields and methods of a user.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here is an example:&lt;/p&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    # Add custom fields if needed
    phone_number = models.CharField(max_length=15, blank=True, null=True)

    def __str__(self):
        return self.username&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This class:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Inherits from AbstractUser, which includes fields like username, email, password, etc.&lt;/li&gt;
&lt;li&gt;Adds an optional phone_number field for additional functionality.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can now use this User model as the user model for your project.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Step 3: Set AUTH_USER_MODEL&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In the settings.py file, add the following:&lt;/p&gt;
&lt;pre class=&quot;ini&quot; data-code-block-lang=&quot;ini&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;AUTH_USER_MODEL = &quot;api.User&quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The AUTH_USER_MODEL setting tells Django to use your custom user model (api.User) instead of the default auth.User model.&lt;/p&gt;
&lt;blockquote data-ke-style=&quot;style1&quot;&gt;&lt;b&gt;Is &lt;/b&gt;&lt;b&gt;AUTH_USER_MODEL&lt;/b&gt;&lt;b&gt; a Predefined Keyword in Django?&lt;/b&gt; Yes, AUTH_USER_MODEL is a predefined setting in Django. By default, it is set to 'auth.User', which refers to Django&amp;rsquo;s built-in user model. When you create a custom user model, this setting must explicitly point to your model in the format '&amp;lt;app_name&amp;gt;.&amp;lt;model_name&amp;gt;'.&lt;/blockquote&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;&amp;nbsp;Why Do We Need AUTH_USER_MODEL?&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;If you don&amp;rsquo;t set AUTH_USER_MODEL and try to use a custom user model, Django will still reference the default auth.User. This creates conflicts, especially when you have relationships like groups or permissions in your custom user model.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;For example, without AUTH_USER_MODEL, you may encounter the following error:&lt;/p&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:
api.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'api.User.groups' clashes with reverse accessor for 'auth.User.groups'.
        HINT: Add or change a related_name argument to the definition for 'api.User.groups' or 'auth.User.groups'.&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This happens because Django tries to create reverse relationships for both auth.User and your custom user model. By setting AUTH_USER_MODEL, you prevent Django from referencing auth.User, resolving such conflicts.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Step 4: Apply Migrations&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;After defining your custom user model and setting AUTH_USER_MODEL, apply the migrations:&lt;/p&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;python manage.py makemigrations
python manage.py migrate&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Django will now create the database schema for your custom user model.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Common Issues and&amp;nbsp;Fixes&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Problem: SystemCheckError (Reverse Accessor&amp;nbsp;Clash)&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;As mentioned earlier, this error occurs when Django tries to reference both the default auth.User and your custom user model. The conflict arises because both models attempt to define reverse relationships with groups and permissions.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Solution&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The solution is to set AUTH_USER_MODEL to your custom user model in settings.py:&lt;/p&gt;
&lt;pre class=&quot;ini&quot; data-code-block-lang=&quot;ini&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;AUTH_USER_MODEL = &quot;api.User&quot;&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This ensures that Django uses your custom user model exclusively.&lt;/p&gt;</description>
      <category>Django Essentials</category>
      <category>api.user.groups</category>
      <category>auth_user_model</category>
      <category>auth_user_model setting</category>
      <category>django custom user model</category>
      <category>systemcheckerror</category>
      <category>user authentication django</category>
      <category>장고 사용자 모델 확장</category>
      <category>장고 커스텀 유저 모델</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/28</guid>
      <comments>https://codeaddict.tistory.com/entry/Django-REST-Framework001-Using-a-Custom-User-Model#entry28comment</comments>
      <pubDate>Mon, 27 Jan 2025 10:48:18 +0900</pubDate>
    </item>
    <item>
      <title>cpp_010: Arrays in C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp010-Arrays-in-C</link>
      <description>&lt;div&gt;&lt;span style=&quot;letter-spacing: 0px;&quot;&gt;Arrays are one of the most fundamental data structures in C++, allowing you to store multiple values of the same type in a single container. In this lesson, we&amp;rsquo;ll introduce arrays, explain their syntax, and provide two examples &amp;mdash; one basic and one advanced &amp;mdash; to showcase their usage.&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. What is an&amp;nbsp;Array?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;An array is a collection of elements stored in contiguous memory locations, all of which share the same data type. You can think of it as a list of values indexed starting from 0.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Declaring and Initializing an&amp;nbsp;Array&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To declare an array in C++, use the following syntax:&lt;/p&gt;
&lt;pre class=&quot;elm&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;type arrayName[size];&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;type&lt;/b&gt;: The data type of the array elements (e.g., int, float, char).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;arrayName&lt;/b&gt;: The name of the array.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;size&lt;/b&gt;: The number of elements the array can hold.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can initialize an array during declaration:&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;int numbers[5] = {10, 20, 30, 40, 50};&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Example 1: Basic&amp;nbsp;Array&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s create a program that prints all elements of an integer array.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50}; // Declaration and initialization

    cout &amp;lt;&amp;lt; &quot;Array Elements:&quot; &amp;lt;&amp;lt; endl;
    for (int i = 0; i &amp;lt; 5; i++) { // Loop through the array
        cout &amp;lt;&amp;lt; &quot;numbers[&quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; &quot;] = &quot; &amp;lt;&amp;lt; numbers[i] &amp;lt;&amp;lt; endl;
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;javascript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Array Elements:  
numbers[0] = 10  
numbers[1] = 20  
numbers[2] = 30  
numbers[3] = 40  
numbers[4] = 50&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The for loop iterates over the array indices from 0 to 4.&lt;/li&gt;
&lt;li&gt;The array elements are accessed using numbers[i].&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4. Example 2: Array with User&amp;nbsp;Input&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this example, we&amp;rsquo;ll calculate the average of numbers entered by the user.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    const int SIZE = 5;
    float numbers[SIZE];
    float sum = 0.0;

    cout &amp;lt;&amp;lt; &quot;Enter &quot; &amp;lt;&amp;lt; SIZE &amp;lt;&amp;lt; &quot; numbers:&quot; &amp;lt;&amp;lt; endl;

    // Taking user input
    for (int i = 0; i &amp;lt; SIZE; i++) {
        cin &amp;gt;&amp;gt; numbers[i];
        sum += numbers[i]; // Accumulating the sum
    }

    // Calculating the average
    float average = sum / SIZE;

    // Displaying the array and average
    cout &amp;lt;&amp;lt; &quot;Array Elements:&quot; &amp;lt;&amp;lt; endl;
    for (int i = 0; i &amp;lt; SIZE; i++) {
        cout &amp;lt;&amp;lt; &quot;numbers[&quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; &quot;] = &quot; &amp;lt;&amp;lt; numbers[i] &amp;lt;&amp;lt; endl;
    }
    cout &amp;lt;&amp;lt; &quot;Average: &quot; &amp;lt;&amp;lt; average &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output (Example):&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Enter 5 numbers:  
10  
20  
30  
40  
50  
Array Elements:  
numbers[0] = 10  
numbers[1] = 20  
numbers[2] = 30  
numbers[3] = 40  
numbers[4] = 50  
Average: 30&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The program prompts the user to input 5 numbers.&lt;/li&gt;
&lt;li&gt;The for loop calculates the sum while storing the numbers in the array.&lt;/li&gt;
&lt;li&gt;The average is computed and displayed along with the array elements.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;</description>
      <category>C++ Beginner</category>
      <category>c++ arrays</category>
      <category>c++ tutorials</category>
      <category>C++ 배열</category>
      <category>c++ 튜토리얼</category>
      <category>배열 초기화</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/27</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp010-Arrays-in-C#entry27comment</comments>
      <pubDate>Sun, 26 Jan 2025 19:09:23 +0900</pubDate>
    </item>
    <item>
      <title>CSS_003_Understanding Descendant and Child Selectors in C</title>
      <link>https://codeaddict.tistory.com/entry/CSS003Understanding-Descendant-and-Child-Selectors-in-C</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this blog post, we&amp;rsquo;ll dive into two important CSS selectors: descendant and child selectors. Understanding these will help you write precise and efficient styles for your HTML elements. Let&amp;rsquo;s explore these concepts with examples and practical code snippets.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;HTML Structure&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s the HTML structure for this lesson:&lt;/p&gt;
&lt;pre class=&quot;xml&quot; data-code-block-lang=&quot;xml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;
  &amp;lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&amp;gt;
  &amp;lt;title&amp;gt;CSS Selectors&amp;lt;/title&amp;gt;
  &amp;lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;ul&amp;gt;
    &amp;lt;li&amp;gt;Direct Child 1&amp;lt;/li&amp;gt;    
    &amp;lt;ol&amp;gt;
      &amp;lt;li&amp;gt;Nested Child 1&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;Nested Child 2&amp;lt;/li&amp;gt;
    &amp;lt;/ol&amp;gt;
    &amp;lt;li&amp;gt;Direct Child 1&amp;lt;/li&amp;gt;
  &amp;lt;/ul&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;CSS Styles&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s the CSS file (main.css) used to demonstrate descendant and child selectors:&lt;/p&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;/* Descendant Selector */
ul li {
  color: black;
  font-size: 20px; /* Applies to all &amp;lt;li&amp;gt; elements within a &amp;lt;ul&amp;gt;, at any level */
}

/* Child Selector */
ul &amp;gt; li {
  color: green; /* Applies only to direct &amp;lt;li&amp;gt; children of the &amp;lt;ul&amp;gt; */
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Descendant Selector (&amp;nbsp;)&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The descendant selector targets all nested elements of a specified parent, regardless of how deep they are in the hierarchy.&lt;br /&gt;&lt;b&gt;Example in Action:&lt;/b&gt;&lt;br /&gt;For the HTML structure above, the CSS rule ul li will apply the styles to:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&amp;ldquo;Direct Child 1&amp;rdquo;&lt;/li&gt;
&lt;li&gt;&amp;ldquo;Nested Child 1&amp;rdquo;&lt;/li&gt;
&lt;li&gt;&amp;ldquo;Nested Child 2&amp;rdquo;&lt;/li&gt;
&lt;li&gt;&amp;ldquo;Direct Child 2&amp;rdquo;&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This makes descendant selectors useful when you want to style all child elements, no matter their nesting level.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Child Selector&amp;nbsp;(&amp;gt;)&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The child selector, on the other hand, targets only the direct children of a parent element.&lt;br /&gt;&lt;b&gt;Example in Action:&lt;/b&gt;&lt;br /&gt;For the CSS rule ul &amp;gt; li, only &quot;Direct Child 1&quot; and &quot;Direct Child 2&quot; will be styled, leaving &quot;Nested Child 1&quot; and &quot;Nested Child 2&quot; unaffected.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This selector is perfect when you want to limit your styles to elements that are directly inside a parent.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Visualizing the Difference&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s a quick summary to help differentiate:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;ul li &amp;rarr; Styles all &amp;lt;li&amp;gt; elements nested inside a &amp;lt;ul&amp;gt;.&lt;/li&gt;
&lt;li&gt;ul &amp;gt; li &amp;rarr; Styles only the immediate &amp;lt;li&amp;gt; children of a &amp;lt;ul&amp;gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Understanding how to use descendant and child selectors effectively allows you to manage complex layouts with greater control. In the next post, we&amp;rsquo;ll explore advanced CSS combinators for even more powerful styling.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Web Development Basics (CSS, JavaScript,</category>
      <category>child selector</category>
      <category>css selectors</category>
      <category>CSS 선택자</category>
      <category>css로 리스트 스타일링</category>
      <category>Descendant Selector</category>
      <category>html styling</category>
      <category>html 스타일링</category>
      <category>자식 선택자</category>
      <category>후손 선택자</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/26</guid>
      <comments>https://codeaddict.tistory.com/entry/CSS003Understanding-Descendant-and-Child-Selectors-in-C#entry26comment</comments>
      <pubDate>Sun, 26 Jan 2025 17:15:41 +0900</pubDate>
    </item>
    <item>
      <title>cpp_009: While Loops and Break Statement in&amp;nbsp;C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp009-While-Loops-and-Break-Statement-in-C</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Loops allow for repeated execution of code blocks, and the while loop is a foundational construct in C++ for controlling repetition based on a condition. In this lesson, we&amp;rsquo;ll cover the syntax of the while loop, demonstrate a basic example, and introduce the break statement for enhanced control flow.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;1. While Loop&amp;nbsp;Syntax&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A while loop in C++ repeatedly executes a block of code as long as its condition evaluates to true.&lt;/p&gt;
&lt;pre class=&quot;smali&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;while (condition) {
    // Code block to execute
}&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Condition&lt;/b&gt;: The loop continues to run as long as this evaluates to true.&lt;/li&gt;
&lt;li&gt;The loop terminates when the condition becomes false.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;2. Example 1: Basic While&amp;nbsp;Loop&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This example prints numbers from 1 to 5 using a while loop.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    int i = 1;  // Initialization
    while (i &amp;lt;= 5) {  // Condition
        cout &amp;lt;&amp;lt; &quot;Number: &quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; endl;
        i++;  // Increment
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;javascript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;The loop starts with i = 1.&lt;/li&gt;
&lt;li&gt;The condition i &amp;lt;= 5 ensures the loop runs five times.&lt;/li&gt;
&lt;li&gt;The i++ increments the variable i with each iteration, moving toward the loop's termination.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;3. Example 2: Using break in a While&amp;nbsp;Loop&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The break statement is used to exit a loop prematurely, regardless of the condition. Here&amp;rsquo;s an example that demonstrates how to use it effectively.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    int i = 1;  // Initialization
    while (true) {  // Infinite loop
        if (i &amp;gt; 5) {  // Break condition
            break;
        }
        cout &amp;lt;&amp;lt; &quot;Number: &quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; endl;
        i++;
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;javascript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;The while (true) creates an infinite loop.&lt;/li&gt;
&lt;li&gt;The if (i &amp;gt; 5) checks whether i exceeds 5.&lt;/li&gt;
&lt;li&gt;When i &amp;gt; 5, the break statement terminates the loop, skipping the remaining iterations.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Summary&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The while loop is a versatile tool for repeating tasks, especially when the number of iterations is not predetermined. The break statement enhances its flexibility, allowing you to exit the loop under specific conditions.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>breakstatement사용법</category>
      <category>c++loopcontrol</category>
      <category>c++programming</category>
      <category>c++whileloop</category>
      <category>C++강의</category>
      <category>C++기초</category>
      <category>C++반복문</category>
      <category>whileloop기초</category>
      <category>while과break</category>
      <category>코딩초보자를위한c++</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/25</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp009-While-Loops-and-Break-Statement-in-C#entry25comment</comments>
      <pubDate>Wed, 15 Jan 2025 22:41:29 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_004_ Nested&amp;nbsp;Classes</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate004-Nested-Classes</link>
      <description>&lt;p data-ke-size=&quot;size16&quot;&gt;When working on Python projects, you might encounter situations where a class needs to contain another class. This is where &lt;b&gt;nested classes&lt;/b&gt; can be helpful. In this post, we will understand what nested classes are, when to use them, and how they compare to using two separate classes. Let&amp;rsquo;s begin with a simple example using two separate classes and then explore how the same functionality can be achieved with nested classes.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Two Separate Classes&amp;nbsp;Example&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s take a real-world example of a &lt;b&gt;School&lt;/b&gt; and its &lt;b&gt;Students&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;# Two separate classes
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        return f&quot;My name is {self.name}, and I am {self.age} years old.&quot;

class School:
    def __init__(self, name):
        self.name = name
        self.students = []

    def add_student(self, student):
        self.students.append(student)

    def display_students(self):
        print(f&quot;Students in {self.name}:&quot;)
        for student in self.students:
            print(student.introduce())

# Usage
school = School(&quot;Greenwood High&quot;)
student1 = Student(&quot;Alice&quot;, 15)
student2 = Student(&quot;Bob&quot;, 16)

school.add_student(student1)
school.add_student(student2)
school.display_students()&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output:&lt;/h4&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;csharp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Students in Greenwood High:
My name is Alice, and I am 15 years old.
My name is Bob, and I am 16 years old.&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;How It&amp;nbsp;Works:&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;We have two separate classes: Student and School.&lt;/li&gt;
&lt;li&gt;The School class uses Student objects to store information about its students.&lt;/li&gt;
&lt;li&gt;While this approach works well, it creates &lt;b&gt;two separate classes&lt;/b&gt; that exist independently in the global namespace.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Nested Classes&amp;nbsp;Example&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now let&amp;rsquo;s refactor the above example to use a &lt;b&gt;nested class&lt;/b&gt;. Here, we&amp;rsquo;ll define the Student class inside the School class:&lt;/p&gt;
&lt;pre class=&quot;ruby&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;# Nested class example
class School:
    def __init__(self, name):
        self.name = name
        self.students = []

    # Define the Student class inside School
    class Student:
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def introduce(self):
            return f&quot;My name is {self.name}, and I am {self.age} years old.&quot;

    def add_student(self, name, age):
        # Create a Student object using the nested class
        student = self.Student(name, age)
        self.students.append(student)

    def display_students(self):
        print(f&quot;Students in {self.name}:&quot;)
        for student in self.students:
            print(student.introduce())

# Usage
school = School(&quot;Greenwood High&quot;)
school.add_student(&quot;Alice&quot;, 15)
school.add_student(&quot;Bob&quot;, 16)
school.display_students()&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output:&lt;/h4&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;csharp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Students in Greenwood High:
My name is Alice, and I am 15 years old.
My name is Bob, and I am 16 years old.&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Differences Between the Two Approaches&lt;/h3&gt;
&lt;p&gt;&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;746&quot; data-origin-height=&quot;469&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/d8re4p/btsLJzpQuLN/dh2zcW1hxbc3rpawkyh7hk/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/d8re4p/btsLJzpQuLN/dh2zcW1hxbc3rpawkyh7hk/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/d8re4p/btsLJzpQuLN/dh2zcW1hxbc3rpawkyh7hk/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fd8re4p%2FbtsLJzpQuLN%2Fdh2zcW1hxbc3rpawkyh7hk%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;746&quot; height=&quot;469&quot; data-origin-width=&quot;746&quot; data-origin-height=&quot;469&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;
&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;When to Use Nested&amp;nbsp;Classes&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Use nested classes when:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Tight Coupling:&lt;/b&gt; The inner class (e.g., Student) is only relevant to the outer class (e.g., School).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Encapsulation:&lt;/b&gt; You want to hide the inner class from external use to reduce clutter in the global namespace.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Logical Grouping:&lt;/b&gt; Grouping related logic together makes your code easier to read and maintain.&lt;/li&gt;
&lt;/ol&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>encapsulation in python</category>
      <category>python nested classes</category>
      <category>중첩 클래스와 독립 클래스 비교</category>
      <category>파이썬 클래스 튜토리얼</category>
      <category>파이썬에서 캡슐화</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/24</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate004-Nested-Classes#entry24comment</comments>
      <pubDate>Sun, 12 Jan 2025 22:29:57 +0900</pubDate>
    </item>
    <item>
      <title>cpp_008: for Loops in&amp;nbsp;C++</title>
      <link>https://codeaddict.tistory.com/entry/cpp008-for-Loops-in-C</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Loops are essential in programming, and the &lt;b&gt;for loop&lt;/b&gt; in C++ is one of the most versatile tools for iterating over sequences or performing repetitive tasks. In this tutorial, we&amp;rsquo;ll start with the &lt;b&gt;syntax&lt;/b&gt; of the for loop and explore &lt;b&gt;three examples&lt;/b&gt;, progressing from basic to more advanced scenarios.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. For Loop&amp;nbsp;Syntax&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A for loop in C++ consists of three components:&lt;/p&gt;
&lt;pre class=&quot;smali&quot; data-code-block-lang=&quot;scss&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;for (initialization; condition; increment/decrement) {
    // Code block to execute
}&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Initialization:&lt;/b&gt; Sets the starting point for the loop (e.g., int i = 0).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Condition:&lt;/b&gt; The loop continues as long as this evaluates to true.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Increment/Decrement:&lt;/b&gt; Updates the loop variable at each iteration.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Example 1: Basic&amp;nbsp;Loop&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This example demonstrates a simple loop that prints numbers from 1 to 5.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    for (int i = 1; i &amp;lt;= 5; i++) {
        cout &amp;lt;&amp;lt; &quot;Number: &quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; endl;
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;int i = 1: Start from 1.&lt;/li&gt;
&lt;li&gt;i &amp;lt;= 5: Continue as long as i is less than or equal to 5.&lt;/li&gt;
&lt;li&gt;i++: Increment i by 1 at each iteration.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Example 2: Loop with Conditionals&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This example adds a conditional statement inside the loop to print even numbers between 1 and 10.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;
int main() {
    for (int i = 1; i &amp;lt;= 10; i++) {
        if (i % 2 == 0) {
            cout &amp;lt;&amp;lt; &quot;Even Number: &quot; &amp;lt;&amp;lt; i &amp;lt;&amp;lt; endl;
        }
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;javascript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Even Number: 2  
Even Number: 4  
Even Number: 6  
Even Number: 8  
Even Number: 10&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The if (i % 2 == 0) condition checks if i is divisible by 2.&lt;/li&gt;
&lt;li&gt;Only even numbers are printed.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4. Example 3: Nested For&amp;nbsp;Loops&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this example, we use &lt;b&gt;nested loops&lt;/b&gt; to display a multiplication table from 1 to 5.&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;
int main() {
    for (int i = 1; i &amp;lt;= 5; i++) {
        for (int j = 1; j &amp;lt;= 5; j++) {
            cout &amp;lt;&amp;lt; i &amp;lt;&amp;lt; &quot; x &quot; &amp;lt;&amp;lt; j &amp;lt;&amp;lt; &quot; = &quot; &amp;lt;&amp;lt; i * j &amp;lt;&amp;lt; &quot;\t&quot;;
        }
        cout &amp;lt;&amp;lt; endl; // New line after each row
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;1 x 1 = 1   1 x 2 = 2   1 x 3 = 3   1 x 4 = 4   1 x 5 = 5  
2 x 1 = 2   2 x 2 = 4   2 x 3 = 6   2 x 4 = 8   2 x 5 = 10  
3 x 1 = 3   3 x 2 = 6   3 x 3 = 9   3 x 4 = 12  3 x 5 = 15  
4 x 1 = 4   4 x 2 = 8   4 x 3 = 12  4 x 4 = 16  4 x 5 = 20  
5 x 1 = 5   5 x 2 = 10  5 x 3 = 15  5 x 4 = 20  5 x 5 = 25&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The outer loop (for i) iterates through rows.&lt;/li&gt;
&lt;li&gt;The inner loop (for j) handles each column in the row.&lt;/li&gt;
&lt;li&gt;i * j computes the product for the multiplication table.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>c++ beginners tutorial</category>
      <category>c++ loops</category>
      <category>c++ multiplication table</category>
      <category>c++ 곱셈표 만들기</category>
      <category>C++ 반복문</category>
      <category>c++ 중첩 루프</category>
      <category>c++ 초보자 튜토리얼</category>
      <category>Nested Loops</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/23</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp008-for-Loops-in-C#entry23comment</comments>
      <pubDate>Sun, 12 Jan 2025 09:09:36 +0900</pubDate>
    </item>
    <item>
      <title>CSS_002_Styling Borders and Backgrounds with HTML and&amp;nbsp;CSS</title>
      <link>https://codeaddict.tistory.com/entry/CSS002Styling-Borders-and-Backgrounds-with-HTML-and-CSS</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this blog post, we&amp;rsquo;ll explore two powerful CSS properties: borders and backgrounds. These properties can help add definition and visual appeal to your HTML elements. Let&amp;rsquo;s dive in with practical examples and explanations.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;HTML Structure&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s the updated HTML structure for this lesson:&lt;/p&gt;
&lt;pre class=&quot;xml&quot; data-code-block-lang=&quot;xml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;
  &amp;lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&amp;gt;
  &amp;lt;title&amp;gt;CSS Styling&amp;lt;/title&amp;gt;
  &amp;lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;div class=&quot;container&quot;&amp;gt;
    &amp;lt;h1&amp;gt;This is my first CSS practice&amp;lt;/h1&amp;gt;
    &amp;lt;h2&amp;gt;CSS is fun&amp;lt;/h2&amp;gt;
  &amp;lt;/div&amp;gt;

  &amp;lt;div&amp;gt;
    &amp;lt;img src=&quot;sun.jpeg&quot; class=&quot;borderImg&quot;&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;CSS Styles&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s the CSS file (main.css) used to style the borders and backgrounds:&lt;/p&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;/* Border Styling */
.borderImg {
  border: 5px solid red; /* Creates a solid red border around the element */
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Border Property&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The border property in CSS allows you to create borders around elements. It consists of three parts:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Width&lt;/b&gt;: Thickness of the border (e.g., 2px, 5px).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Style&lt;/b&gt;: Type of the border (e.g., solid, dashed, dotted, double, etc.).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Color&lt;/b&gt;: The color of the border (e.g., red, blue, or hex codes like #ff0000).&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Example of Different Border&amp;nbsp;Styles:&lt;/h4&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;/* Solid Border */
.solidBorder {
  border: 3px solid blue;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can mix and match these properties to customize your borders.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Background Properties&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The background property in CSS allows you to customize the look and feel of your webpage. You can:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Use images (background-image).&lt;/li&gt;
&lt;li&gt;Control how images repeat (background-repeat).&lt;/li&gt;
&lt;li&gt;Set the image size (background-size).&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Example of Background Styling:&lt;/h4&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;body {
  background-image: url(nature.jpeg);
  background-repeat: no-repeat;
  background-size: cover;

}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s break down each property used in the code:&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;1. background-image&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This property is used to set an image as the background of an element.&lt;br /&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;less&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;background-image: url('image-file-path');&lt;/code&gt;&lt;/pre&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;url('nature.jpeg'): Specifies the path to the image you want to use. In this case, the file nature.jpeg is located in the same directory as the HTML file.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;2. background-repeat&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This property controls whether the background image is repeated.&lt;br /&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;fortran&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;background-repeat: value;&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Values:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;repeat: Default value. The image is repeated both horizontally and vertically.&lt;/li&gt;
&lt;li&gt;repeat-x: The image is repeated horizontally only.&lt;/li&gt;
&lt;li&gt;repeat-y: The image is repeated vertically only.&lt;/li&gt;
&lt;li&gt;no-repeat: The image is not repeated.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In our example, background-repeat: no-repeat; ensures that the image appears only once on the page.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;3. background-size&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This property specifies the size of the background image.&lt;br /&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;background-size: value;&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Values:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;auto: Default value. The image is displayed at its original size.&lt;/li&gt;
&lt;li&gt;cover: Scales the image to completely cover the element's area while maintaining its aspect ratio.&lt;/li&gt;
&lt;li&gt;contain: Scales the image to fit within the element's area while maintaining its aspect ratio.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In our example, background-size: cover; makes the image cover the entire viewport. Even if the viewport size changes (e.g., resizing the browser window), the image will adjust accordingly to cover the full area without distortion.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Final Output&lt;/h3&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;800&quot; data-origin-height=&quot;503&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/dMt1gB/btsLKFvJxyR/xH5vcbzG9srm1kKG82PHB0/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/dMt1gB/btsLKFvJxyR/xH5vcbzG9srm1kKG82PHB0/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/dMt1gB/btsLKFvJxyR/xH5vcbzG9srm1kKG82PHB0/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FdMt1gB%2FbtsLKFvJxyR%2FxH5vcbzG9srm1kKG82PHB0%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;800&quot; height=&quot;503&quot; data-origin-width=&quot;800&quot; data-origin-height=&quot;503&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Web Development Basics (CSS, JavaScript,</category>
      <category>Background</category>
      <category>border</category>
      <category>CSS</category>
      <category>CSS border</category>
      <category>CSS 배경</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/22</guid>
      <comments>https://codeaddict.tistory.com/entry/CSS002Styling-Borders-and-Backgrounds-with-HTML-and-CSS#entry22comment</comments>
      <pubDate>Sun, 12 Jan 2025 08:39:45 +0900</pubDate>
    </item>
    <item>
      <title>CSS_001_Styling Basics with HTML and&amp;nbsp;CSS</title>
      <link>https://codeaddict.tistory.com/entry/CSS001Styling-Basics-with-HTML-and-CSS</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;CSS is a powerful tool that allows you to bring life and style to your HTML elements. In this blog post, we&amp;rsquo;ll look at a simple example of how CSS can transform your webpage with gradients, shadows, and color effects. We&amp;rsquo;ll explain the code step by step to understand how each line contributes to the final result.&lt;/p&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;763&quot; data-origin-height=&quot;134&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/mlwG0/btsLIzVZjXs/7zupgomnEupL9PyE5T4bs1/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/mlwG0/btsLIzVZjXs/7zupgomnEupL9PyE5T4bs1/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/mlwG0/btsLIzVZjXs/7zupgomnEupL9PyE5T4bs1/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FmlwG0%2FbtsLIzVZjXs%2F7zupgomnEupL9PyE5T4bs1%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;763&quot; height=&quot;134&quot; data-origin-width=&quot;763&quot; data-origin-height=&quot;134&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;HTML Structure&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s the simple HTML structure we are working with:&lt;/p&gt;
&lt;pre class=&quot;xml&quot; data-code-block-lang=&quot;xml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;
  &amp;lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&amp;gt;
  &amp;lt;title&amp;gt;CSS Styling&amp;lt;/title&amp;gt;
  &amp;lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;div class =&quot;container&quot;&amp;gt;
  &amp;lt;h1&amp;gt;This is my first CSS practice &amp;lt;/h1&amp;gt;
  &amp;lt;h2&amp;gt;CSS is fun&amp;lt;/h2&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/b&gt;: Declares the document type as HTML5.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;html lang=&quot;en&quot;&amp;gt;&lt;/b&gt;: Specifies that the language of the document is English.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;head&amp;gt;&lt;/b&gt;: Contains metadata and links to external resources.&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;&lt;/b&gt;: Sets the character encoding to UTF-8, allowing a wide range of characters.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&amp;gt;&lt;/b&gt;: Makes the page responsive by setting the viewport width to the device&amp;rsquo;s screen width.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;title&amp;gt;My CSS&amp;lt;/title&amp;gt;&lt;/b&gt;: Sets the title of the webpage (visible on the browser tab).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&amp;gt;&lt;/b&gt;: Links an external CSS file (main.css) to style the HTML elements.&lt;/li&gt;
&lt;/ul&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;body&amp;gt;&lt;/b&gt;: Contains the main content of the webpage.&lt;/li&gt;
&lt;/ol&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;div class=&quot;container&quot;&amp;gt;&lt;/b&gt;: Creates a container div to group and style the content.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;h1&amp;gt;&amp;lt;/h1&amp;gt;&lt;/b&gt;: Defines a level-one heading with the text &quot;You are the CSS.&quot;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&amp;lt;h2&amp;gt;&amp;lt;/h2&amp;gt;&lt;/b&gt;: Defines a level-two heading with the text &quot;Anyone escaped there.&quot;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;CSS Styles&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Here&amp;rsquo;s the CSS used to style the HTML elements:&lt;/p&gt;
&lt;pre class=&quot;css&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;.container {
 
  background: linear-gradient(to left, #9d0dbd, #df9fed);
  box-shadow: 3px 5px 3px blue;
}

h1 {
  color: black;
  text-shadow: 5px 5px 5px rgb(116, 113, 113);

}

h2 {

  color: rgb(5, 116, 22);
  text-shadow: 5px 5px 5px rgb(116, 113, 113);
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation of Each CSS&amp;nbsp;Rule&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;1.&amp;nbsp;.container&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The container class applies styles to the &amp;lt;div&amp;gt; element and everything inside it.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;background: linear-gradient(to left, #9d0dbd, #df9fed);&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;This creates a gradient background that transitions from purple (#9d0dbd) to light pink (#df9fed), moving &lt;b&gt;from right to left&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;color: blue;&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Sets the default text color inside the container to blue.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;box-shadow: 3px 5px 3px blue;&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Adds a shadow around the container. The parameters are:&lt;/li&gt;
&lt;li&gt;&lt;b&gt;3px&lt;/b&gt;: Horizontal shadow.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;5px&lt;/b&gt;: Vertical shadow.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;3px&lt;/b&gt;: Blur radius.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;blue&lt;/b&gt;: Color of the shadow.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;2. h1&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The h1 tag defines the first header.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;color: black;&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Sets the text color to black.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;text-shadow: 10px, 100px;&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;This line is invalid because text-shadow requires four values (x-offset, y-offset, blur-radius, and color). It won&amp;rsquo;t work and should be removed.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;text-shadow: 30px 10px 10px gray;&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Correctly applies a shadow to the text. The parameters are:&lt;/li&gt;
&lt;li&gt;&lt;b&gt;30px&lt;/b&gt;: Horizontal offset (moves shadow to the right).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;10px&lt;/b&gt;: Vertical offset (moves shadow down).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;10px&lt;/b&gt;: Blur radius (softens the shadow edges).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;gray&lt;/b&gt;: Shadow color.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;3. h2&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The h2 tag defines the second header.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;color: rgb(0, 204, 255);&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Sets the text color to a bright cyan using RGB values:&lt;/li&gt;
&lt;li&gt;&lt;b&gt;0&lt;/b&gt;: Red intensity.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;204&lt;/b&gt;: Green intensity.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;255&lt;/b&gt;: Blue intensity.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Final Result&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;When the above code is executed, here&amp;rsquo;s what you will see:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;A &lt;b&gt;container&lt;/b&gt; with a gradient background (purple to pink) and a &lt;b&gt;blue shadow&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;A &lt;b&gt;level-one heading&lt;/b&gt; (h1) with black text and a gray shadow that appears offset and slightly blurred.&lt;/li&gt;
&lt;li&gt;A &lt;b&gt;level-two heading&lt;/b&gt; (h2) with bright cyan text.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure class=&quot;imageblock alignCenter&quot; data-ke-mobileStyle=&quot;widthOrigin&quot; data-origin-width=&quot;763&quot; data-origin-height=&quot;134&quot;&gt;&lt;span data-url=&quot;https://blog.kakaocdn.net/dn/qdFI0/btsLIOekuzo/ngE8lWKfL8Zk6ZMen7mRuk/img.png&quot; data-phocus=&quot;https://blog.kakaocdn.net/dn/qdFI0/btsLIOekuzo/ngE8lWKfL8Zk6ZMen7mRuk/img.png&quot;&gt;&lt;img src=&quot;https://blog.kakaocdn.net/dn/qdFI0/btsLIOekuzo/ngE8lWKfL8Zk6ZMen7mRuk/img.png&quot; srcset=&quot;https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FqdFI0%2FbtsLIOekuzo%2FngE8lWKfL8Zk6ZMen7mRuk%2Fimg.png&quot; onerror=&quot;this.onerror=null; this.src='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png'; this.srcset='//t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png';&quot; loading=&quot;lazy&quot; width=&quot;763&quot; height=&quot;134&quot; data-origin-width=&quot;763&quot; data-origin-height=&quot;134&quot;/&gt;&lt;/span&gt;&lt;/figure&gt;

&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Web Development Basics (CSS, JavaScript,</category>
      <category>CSS</category>
      <category>css beginner</category>
      <category>css 초보자</category>
      <category>HTML</category>
      <category>shadow</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/21</guid>
      <comments>https://codeaddict.tistory.com/entry/CSS001Styling-Basics-with-HTML-and-CSS#entry21comment</comments>
      <pubDate>Wed, 8 Jan 2025 21:57:28 +0900</pubDate>
    </item>
    <item>
      <title>cpp_007:Introduction to String Modifiers in C++&amp;nbsp;, Mastering String Manipulation</title>
      <link>https://codeaddict.tistory.com/entry/cpp007Introduction-to-String-Modifiers-in-C-Mastering-String-Manipulation</link>
      <description>&lt;p data-ke-size=&quot;size16&quot;&gt;In C++, the std::string class provides a variety of functions to modify and manipulate strings efficiently. This tutorial is perfect for beginners looking to master string operations such as appending, erasing, inserting, finding, replacing, and more. Let&amp;rsquo;s dive into these powerful tools with examples and outputs.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. Appending to a&amp;nbsp;String&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The append() function and the + operator allow you to concatenate strings.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;string.append(str) - Appends the string str to the end of the string.&lt;/li&gt;
&lt;li&gt;string + str - Concatenates str to the string.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 1: Appending Strings&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string greeting = &quot;Hello&quot;;
    string name = &quot;World&quot;;

    // Using append()
    greeting.append(&quot;, &quot;).append(name);
    cout &amp;lt;&amp;lt; &quot;Greeting with append: &quot; &amp;lt;&amp;lt; greeting &amp;lt;&amp;lt; endl;

    // Using + operator
    string fullGreeting = greeting + &quot;!&quot;;
    cout &amp;lt;&amp;lt; &quot;Final Greeting: &quot; &amp;lt;&amp;lt; fullGreeting &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;gradle&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Greeting with append: Hello, World
Final Greeting: Hello, World!&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Erasing Characters or Substrings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The erase() function removes characters from a string.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;string.erase(index, length) - Removes length characters starting from index.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 2: Erasing a Substring&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string sentence = &quot;The quick brown fox jumps over the lazy dog.&quot;;

    // Removing a substring
    sentence.erase(4, 6);  // Remove &quot;quick &quot; (starting at index 4, length 6)
    cout &amp;lt;&amp;lt; &quot;After erase: &quot; &amp;lt;&amp;lt; sentence &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;mipsasm&quot; data-code-block-lang=&quot;sql&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;After erase: The brown fox jumps over the lazy dog.&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Inserting into a&amp;nbsp;String&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The insert() function adds characters or substrings at a specific index.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;string.insert(index, str) - Inserts the string str at the specified index.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 3: Inserting a Substring&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string sentence = &quot;Hello World!&quot;;

    // Insert a substring
    sentence.insert(6, &quot;Beautiful &quot;);
    cout &amp;lt;&amp;lt; &quot;After insert: &quot; &amp;lt;&amp;lt; sentence &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;mipsasm&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;After insert: Hello Beautiful World!&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4. Finding and Replacing Substrings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The find() function locates the first occurrence of a substring, while replace() replaces a portion of the string.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;string.find(str) - Returns the index of the first occurrence of str or string::npos if not found.&lt;/li&gt;
&lt;li&gt;string.replace(index, length, str) - Replaces length characters starting at index with str.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 4: Find and Replace&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string sentence = &quot;I love apples.&quot;;

    // Finding a substring
    size_t pos = sentence.find(&quot;apples&quot;);
    if (pos != string::npos) {
        // Replacing the substring
        sentence.replace(pos, 6, &quot;oranges&quot;);
    }
    cout &amp;lt;&amp;lt; &quot;After replace: &quot; &amp;lt;&amp;lt; sentence &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;coq&quot; data-code-block-lang=&quot;less&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;After replace: I love oranges.&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;5. Extracting Substrings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The substr() function retrieves a portion of the string.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;string.substr(index, length) - Returns a substring starting at index with length characters.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 5: Substring Extraction&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string sentence = &quot;The quick brown fox&quot;;

    // Extracting a substring
    string word = sentence.substr(10, 5);  // Starting at index 10, length 5
    cout &amp;lt;&amp;lt; &quot;Extracted word: &quot; &amp;lt;&amp;lt; word &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;applescript&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Extracted word: brown&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;6. Comparing Strings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The compare() function compares two strings lexicographically.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;string.compare(str) - Returns:&lt;/li&gt;
&lt;li&gt;A negative value if the string is less than str.&lt;/li&gt;
&lt;li&gt;Zero if the string is equal to str.&lt;/li&gt;
&lt;li&gt;A positive value if the string is greater than str.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 6: Comparing Strings&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string str1 = &quot;apple&quot;;
    string str2 = &quot;banana&quot;;

    int result = str1.compare(str2);
    if (result &amp;lt; 0) {
        cout &amp;lt;&amp;lt; str1 &amp;lt;&amp;lt; &quot; comes before &quot; &amp;lt;&amp;lt; str2 &amp;lt;&amp;lt; &quot; in lexicographical order.&quot; &amp;lt;&amp;lt; endl;
    } else if (result &amp;gt; 0) {
        cout &amp;lt;&amp;lt; str1 &amp;lt;&amp;lt; &quot; comes after &quot; &amp;lt;&amp;lt; str2 &amp;lt;&amp;lt; &quot; in lexicographical order.&quot; &amp;lt;&amp;lt; endl;
    } else {
        cout &amp;lt;&amp;lt; str1 &amp;lt;&amp;lt; &quot; is equal to &quot; &amp;lt;&amp;lt; str2 &amp;lt;&amp;lt; &quot;.&quot; &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;armasm&quot; data-code-block-lang=&quot;css&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;apple comes before banana in lexicographical order.&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;7. Removing the Last Character&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The pop_back() function removes the last character of the string.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Syntax:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;string.pop_back() - Removes the last character of the string.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Example 7: Removing the Last Character&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string sentence = &quot;Hello World!&quot;;

    // Removing the last character
    sentence.pop_back();
    cout &amp;lt;&amp;lt; &quot;After pop_back: &quot; &amp;lt;&amp;lt; sentence &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;armasm&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;After pop_back: Hello World&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;By mastering these string modifiers, you can handle any string manipulation task in C++ with confidence. Practice these examples and try combining multiple functions to solve more complex problems.&amp;nbsp;&lt;/p&gt;</description>
      <category>C++ Beginner</category>
      <category>c++ 문자열</category>
      <category>c++ 초보자 가이드</category>
      <category>c++ 코딩 입문</category>
      <category>String 클래스</category>
      <category>문자열 삭제</category>
      <category>문자열 삽입</category>
      <category>문자열 수정</category>
      <category>문자열 함수 문법</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/20</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp007Introduction-to-String-Modifiers-in-C-Mastering-String-Manipulation#entry20comment</comments>
      <pubDate>Mon, 6 Jan 2025 23:00:43 +0900</pubDate>
    </item>
    <item>
      <title>cpp_006_Introduction to getline and cin.getline in C++: Handling User Input with&amp;nbsp;Spaces</title>
      <link>https://codeaddict.tistory.com/entry/cpp006Introduction-to-getline-and-cingetline-in-C-Handling-User-Input-with-Spaces</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In C++, reading strings can be tricky when the input contains spaces. For instance, the default cin input method stops reading input when it encounters a whitespace character. In this tutorial, we&amp;rsquo;ll explore how to handle input with spaces using getline() and cin.getline().&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. Problem with cin and&amp;nbsp;Spaces&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;By default, when you use cin &amp;gt;&amp;gt; variable, it reads input until it encounters a whitespace (space, tab, or newline). This makes it difficult to read full sentences or strings with spaces.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Code Example:&lt;/b&gt;&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Example 1: Input with Multiple&amp;nbsp;Words&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s examine an example where multiple words are entered, and we see how cin &amp;gt;&amp;gt; processes them:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string firstWord;
    string leftover1;
    string leftover2;
    string leftover3;
    string leftover4;

    // Using cin to read input (stops at space)
    cout &amp;lt;&amp;lt; &quot;Enter a greeting: &quot;;
    cin &amp;gt;&amp;gt; firstWord;  // Reads the first word only
    cout &amp;lt;&amp;lt; &quot;You entered: &quot; &amp;lt;&amp;lt; firstWord &amp;lt;&amp;lt; endl;

    // Reading leftover input after the first word
    cin &amp;gt;&amp;gt; leftover1;  // Reads the next word
    cout &amp;lt;&amp;lt; &quot;Leftover input: &quot; &amp;lt;&amp;lt; leftover1 &amp;lt;&amp;lt; endl;

    cin &amp;gt;&amp;gt; leftover2;  // Reads the next word
    cout &amp;lt;&amp;lt; &quot;Leftover input: &quot; &amp;lt;&amp;lt; leftover2 &amp;lt;&amp;lt; endl;

    cin &amp;gt;&amp;gt; leftover3;  // Reads the next word
    cout &amp;lt;&amp;lt; &quot;Leftover input: &quot; &amp;lt;&amp;lt; leftover3 &amp;lt;&amp;lt; endl;

    cin &amp;gt;&amp;gt; leftover4;  // Reads the next word
    cout &amp;lt;&amp;lt; &quot;Leftover input: &quot; &amp;lt;&amp;lt; leftover4 &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Example 1: Case 1 &amp;mdash; Input: &amp;ldquo;fd&amp;nbsp;dfd&amp;rdquo;&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;If you input fd dfd and press Enter:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;The first cin &amp;gt;&amp;gt; firstWord; reads fd (only the first word before the space).&lt;/li&gt;
&lt;li&gt;The following cin &amp;gt;&amp;gt; leftoverX; calls will read the next words from the leftover input.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Enter a greeting: hi there
You entered: hi
Leftover input: there

&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;cin &amp;gt;&amp;gt; firstWord; captures hi (first word).&lt;/li&gt;
&lt;li&gt;The space after hi is left in the input buffer.&lt;/li&gt;
&lt;li&gt;cin &amp;gt;&amp;gt; leftover1; reads there, as it&amp;rsquo;s the next available word in the buffer.&lt;/li&gt;
&lt;li&gt;Since there are no more words in the buffer after there, the remaining cin &amp;gt;&amp;gt; leftover2, cin &amp;gt;&amp;gt; leftover3, and cin &amp;gt;&amp;gt; leftover4 calls result in no input being captured.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Example 1: Case 2 &amp;mdash; Input: &amp;ldquo;hello today is cold, what are you&amp;nbsp;wearing&amp;rdquo;&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, if you input a longer sentence like hello today is cold, what are you wearing:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;cin &amp;gt;&amp;gt; firstWord; reads hello (the first word before the first space).&lt;/li&gt;
&lt;li&gt;The following cin &amp;gt;&amp;gt; leftoverX; calls will read one word at a time from the remaining input.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Enter a greeting: hello today is cold, what are you wearing
You entered: hello
Leftover input: today
Leftover input: is
Leftover input: cold,
Leftover input: what&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;cin &amp;gt;&amp;gt; firstWord; captures hello.&lt;/li&gt;
&lt;li&gt;The space after hello is left in the buffer, so the next cin &amp;gt;&amp;gt; leftover1; reads today.&lt;/li&gt;
&lt;li&gt;After reading today, the space after it leaves the buffer, so cin &amp;gt;&amp;gt; leftover2; captures is.&lt;/li&gt;
&lt;li&gt;This continues until all words are processed, one by one, in each call to cin &amp;gt;&amp;gt; leftoverX;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This shows that cin &amp;gt;&amp;gt; captures one word at a time, and any remaining words are handled in subsequent calls to cin &amp;gt;&amp;gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. When to Use getline() to Capture Full Sentences&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;To handle input with spaces properly and capture full sentences or phrases, cin &amp;gt;&amp;gt; is not sufficient because it only reads one word at a time. Instead, we use getline() to read the entire line of input, including spaces.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Modified Code Using getline() to Capture Full Sentences:&lt;/h4&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    string fullInput;

    // Using getline() to read a full line of input, including spaces
    cout &amp;lt;&amp;lt; &quot;Enter a full sentence: &quot;;
    getline(cin, fullInput);  // Reads the entire line
    cout &amp;lt;&amp;lt; &quot;You entered: &quot; &amp;lt;&amp;lt; fullInput &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Output:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;inform7&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Enter a full sentence: hello today is cold, what are you wearing
You entered: hello today is cold, what are you wearing&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Explanation:&lt;/b&gt;&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;getline(cin, fullInput); reads the entire line of input, including spaces between words.&lt;/li&gt;
&lt;li&gt;It captures the full sentence hello today is cold, what are you wearing in the fullInput string.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Using cin.getline() for Fixed-Length Input&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;cin.getline() is another version of getline() but with an additional feature. It allows you to specify the maximum number of characters that can be read. If the input exceeds this limit, it will be truncated, and any excess characters will remain in the input buffer for future use.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;Code Example:&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    char greeting[50];  // Buffer size

    // Using cin.getline() to read up to 50 characters
    cout &amp;lt;&amp;lt; &quot;Enter a greeting: &quot;;
    cin.getline(greeting, 50);
    cout &amp;lt;&amp;lt; &quot;You entered: &quot; &amp;lt;&amp;lt; greeting &amp;lt;&amp;lt; endl;

    return 0;
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Output:&lt;/p&gt;
&lt;pre class=&quot;groovy&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Enter a greeting: Hello there, how are you doing?
You entered: Hello there, how are you doing?&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4. Key Differences Between getline() and cin.getline()&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;getline(cin, string) works with std::string and automatically adjusts the string size.&lt;/li&gt;
&lt;li&gt;cin.getline(char array[], size) works with character arrays and requires you to define a fixed size for the buffer.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Handling user input in C++ can be challenging when the input contains spaces. The default cin &amp;gt;&amp;gt; behavior stops at spaces, but by using getline() or cin.getline(), you can easily capture full sentences or control the size of the input buffer. Understanding these functions helps you better manage user input and avoid common pitfalls.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>cin.getline() #</category>
      <category>CPP</category>
      <category>getline()</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/19</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp006Introduction-to-getline-and-cingetline-in-C-Handling-User-Input-with-Spaces#entry19comment</comments>
      <pubDate>Sun, 5 Jan 2025 23:12:33 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_005: Working with the Requests&amp;nbsp;Library</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate004-Working-with-the-Requests-Library</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The requests library in Python is a powerful tool for making HTTP requests, allowing you to interact with APIs, fetch data from websites, and send data to servers. It's simple, user-friendly, and perfect for beginners.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Installation&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Install the requests library using pip if you don&amp;rsquo;t have it installed:&lt;/p&gt;
&lt;pre class=&quot;cmake&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;pip install requests&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Features and&amp;nbsp;Examples&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Let&amp;rsquo;s dive into the most useful and practical use cases for the requests library, with clear explanations and code examples.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. Making a Simple GET&amp;nbsp;Request&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A GET request is used to fetch data from a server.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code Example:&lt;/h4&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;import requests

response = requests.get(&quot;https://api.github.com&quot;)
print(&quot;Status Code:&quot;, response.status_code)
print(&quot;Response Body:&quot;, response.text)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;1. response.status_code&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Displays the HTTP status code (e.g., 200 for success, 404 for not found).&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. response.text&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Prints the response body (data returned by the server) as a string.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output:&lt;/h4&gt;
&lt;pre class=&quot;armasm&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Status Code: 200
Response Body: {
  &quot;current_user_url&quot;: &quot;https://api.github.com/user&quot;,
  &quot;current_user_authorizations_html_url&quot;: &quot;https://github.com/settings/connections/applications{/client_id}&quot;,
  ...
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Sending URL Parameters in a GET&amp;nbsp;Request&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Query parameters are added to a URL to filter or modify the data returned by the server.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code Example:&lt;/h4&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;import requests

url = &quot;https://api.github.com/search/repositories&quot;
params = {&quot;q&quot;: &quot;requests+language:python&quot;}  # Search for Python repositories about &quot;requests&quot;
response = requests.get(url, params=params)

print(&quot;Request URL:&quot;, response.url)
print(&quot;Total Repositories Found:&quot;, response.json().get(&quot;total_count&quot;))&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;1. params&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Used to pass query parameters as a dictionary.&lt;/li&gt;
&lt;li&gt;Converts {&quot;q&quot;: &quot;requests+language:python&quot;} to&amp;nbsp;?q=requests+language:python and appends it to the URL.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. response.url&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Outputs the final URL with parameters:&lt;/li&gt;
&lt;/ul&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;sql&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;https://api.github.com/search/repositories?q=requests+language:python&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;3. response.json()&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Parses the JSON response into a Python dictionary.&lt;/li&gt;
&lt;li&gt;total_count gives the total number of repositories matching the query.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output:&lt;/h4&gt;
&lt;pre class=&quot;vim&quot; data-code-block-lang=&quot;sql&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Request URL: https://api.github.com/search/repositories?q=requests+language:python
Total Repositories Found: 230&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Making a POST&amp;nbsp;Request&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A POST request is used to send data to a server, such as submitting forms.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code Example:&lt;/h4&gt;
&lt;pre class=&quot;makefile&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;import requests

url = &quot;https://httpbin.org/post&quot;
data = {&quot;username&quot;: &quot;test_user&quot;, &quot;password&quot;: &quot;test_pass&quot;}
response = requests.post(url, data=data)

print(&quot;Response JSON:&quot;, response.json())&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;1. data&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Sends form data as a dictionary in the body of the request.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. response.json()&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Parses the JSON response from the server.&lt;/li&gt;
&lt;li&gt;The server at &lt;a href=&quot;https://httpbin.org/post&quot;&gt;https://httpbin.org/post&lt;/a&gt; echoes back the data you send,&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output:&lt;/h4&gt;
&lt;pre class=&quot;1c&quot; data-code-block-lang=&quot;bash&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;Response JSON: {
  &quot;args&quot;: {},
  &quot;data&quot;: &quot;&quot;,
  &quot;files&quot;: {},
  &quot;form&quot;: {
    &quot;password&quot;: &quot;test_pass&quot;,
    &quot;username&quot;: &quot;test_user&quot;
  },
  'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '37', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.32.3', 'X-Amzn-Trace-Id': 'Root=1-6778c520-3c1dde5b75a7d2900d9b00cb'}, 
 'json': None, 
 'origin': 'xxx', 
 'url': 'https://httpbin.org/post'}

}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4. Downloading a&amp;nbsp;File&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can use the requests library to download files like images, PDFs, or other content.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code Example:&lt;/h4&gt;
&lt;pre class=&quot;livecodeserver&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import requests

url = &quot;https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf&quot;
response = requests.get(url)

with open(&quot;dummy.pdf&quot;, &quot;wb&quot;) as file:
    file.write(response.content)
print(&quot;File downloaded successfully!&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;1. response.content&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Returns the binary content of the file (e.g., for PDFs or images).&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Writing to a file&lt;/b&gt;:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Saves the content to dummy.pdf in the current directory using wb (write binary mode).&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output:&lt;/h4&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;File downloaded successfully!&lt;/code&gt;&lt;/pre&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A file named dummy.pdf will be saved in your current directory.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;5. Handling Errors and&amp;nbsp;Timeouts&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;When dealing with external servers, requests might fail. It&amp;rsquo;s important to handle such errors gracefully.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code Example:&lt;/h4&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import requests

url = &quot;https://api.github.com/nonexistent&quot;

try:
    response = requests.get(url, timeout=5)  # Timeout after 5 seconds
    response.raise_for_status()  # Raise an exception for HTTP errors
    print(&quot;Response:&quot;, response.json())
except requests.exceptions.Timeout:
    print(&quot;The request timed out!&quot;)
except requests.exceptions.HTTPError as err:
    print(&quot;HTTP error occurred:&quot;, err)
except requests.exceptions.RequestException as err:
    print(&quot;Other error occurred:&quot;, err)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Timeout&lt;/b&gt;: Limits how long the program waits for a response.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;raise_for_status()&lt;/b&gt;: Throws an exception for HTTP errors like 404.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Error Handling&lt;/b&gt;: Categorizes errors (e.g., timeout, HTTP errors) for better debugging.&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output (Example for a 404&amp;nbsp;Error):&lt;/h4&gt;
&lt;pre class=&quot;groovy&quot; data-code-block-lang=&quot;go&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;HTTP error occurred: 404 Client Error: Not Found for url: https://api.github.com/nonexistent&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;6. Working with JSON&amp;nbsp;Data&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can send JSON data in a POST request and receive JSON responses.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code Example:&lt;/h4&gt;
&lt;pre class=&quot;makefile&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;import requests

url = &quot;https://httpbin.org/post&quot;
json_data = {&quot;key&quot;: &quot;value&quot;, &quot;name&quot;: &quot;Python Requests&quot;}
response = requests.post(url, json=json_data)

print(&quot;Response JSON:&quot;, response.json())&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation:&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;1. json&lt;/b&gt;: Automatically converts the dictionary to JSON format and sets the Content-Type header to application/json.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;2. Response&lt;/b&gt;: The server echoes the JSON data you send.&lt;/p&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Output:&lt;/h4&gt;
&lt;pre class=&quot;jboss-cli&quot; data-code-block-lang=&quot;makefile&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Response JSON: {
  &quot;args&quot;: {},
  &quot;data&quot;: '{&quot;key&quot;: &quot;value1&quot;, &quot;name&quot;: &quot;Python Requests1&quot;}'
  &quot;files&quot;: {},
  &quot;form&quot;: {},
  &quot;headers&quot;: {
    ...
  },
  &quot;json&quot;: {
    &quot;key&quot;: &quot;value&quot;,
    &quot;name&quot;: &quot;Python Requests&quot;
  },
  &quot;url&quot;: &quot;https://httpbin.org/post&quot;
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The requests library is a powerful and easy-to-use tool for making HTTP requests in Python. It covers a wide range of use cases, such as:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;Fetching data from APIs (GET requests).&lt;/li&gt;
&lt;li&gt;Sending data to servers (POST requests).&lt;/li&gt;
&lt;li&gt;Handling errors and timeouts.&lt;/li&gt;
&lt;li&gt;Downloading files or automating tasks like form submissions.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;What Next?&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;Explore advanced topics like authentication (BasicAuth, OAuth).&lt;/li&gt;
&lt;li&gt;Use APIs like OpenWeatherMap, Twitter, or GitHub to practice.&lt;/li&gt;
&lt;li&gt;Learn web scraping with requests + BeautifulSoup.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <category>http 요청</category>
      <category>python requests</category>
      <category>python 튜토리얼</category>
      <category>Requests</category>
      <category>데이터 가져오기</category>
      <category>파이썬</category>
      <category>파이썬 라이브러리</category>
      <category>파이썬 중급</category>
      <category>프로그래밍</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/18</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate004-Working-with-the-Requests-Library#entry18comment</comments>
      <pubDate>Sat, 4 Jan 2025 19:45:30 +0900</pubDate>
    </item>
    <item>
      <title>cpp_005_Introduction to&amp;nbsp;Strings</title>
      <link>https://codeaddict.tistory.com/entry/cpp004Introduction-to-Strings</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;C++ provides two primary ways to work with strings: &lt;b&gt;C-style strings&lt;/b&gt; and the modern &lt;b&gt;std::string&lt;/b&gt;&lt;b&gt; class&lt;/b&gt;. This tutorial covers the key concepts, differences, and practical examples.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. What Are Strings in&amp;nbsp;C++?&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;A string is a sequence of characters. In C++, you can represent strings in two ways:&lt;/p&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;C-style strings&lt;/b&gt;: Arrays of characters ending with a null character (\0).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;std::string&lt;/b&gt;: A part of the C++ Standard Library, providing an easier and safer way to work with strings.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. C-Style&amp;nbsp;Strings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;C-style strings are simply arrays of characters terminated with a null character (\0). You need to manage their size manually.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cstring&amp;gt; // For C-style string functions
using namespace std;

int main() {
    char cstr[] = &quot;Hello, C-style strings!&quot;;
    cout &amp;lt;&amp;lt; &quot;C-Style String: &quot; &amp;lt;&amp;lt; cstr &amp;lt;&amp;lt; endl;

    // String length using strlen()
    cout &amp;lt;&amp;lt; &quot;Length: &quot; &amp;lt;&amp;lt; strlen(cstr) &amp;lt;&amp;lt; endl;

    // Concatenation using strcat()
    char greeting[50] = &quot;Hello&quot;;
    strcat(greeting, &quot;, World!&quot;);
    cout &amp;lt;&amp;lt; &quot;Concatenated String: &quot; &amp;lt;&amp;lt; greeting &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;mathematica&quot; data-code-block-lang=&quot;vbnet&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;C-Style String: Hello, C-style strings!
Length: 22
Concatenated String: Hello, World!&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Key Points:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;strlen(cstr)&lt;/b&gt;: Returns the number of characters (excluding \0).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;strcat()&lt;/b&gt;: Concatenates strings but requires enough space in the destination array.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. std::string Class&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;std::string is a modern and more versatile way to work with strings. It automatically manages memory and provides many useful functions.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3.1 Declaring and Initializing Strings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;If you don&amp;rsquo;t assign a value to a string, it&amp;rsquo;s &lt;b&gt;blank (empty)&lt;/b&gt; by default.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
using namespace std;

int main() {
    string str1 = &quot;Hello, &quot;;
    string str2 = &quot;std::string!&quot;;
    string emptyStr; // Default value is blank

    cout &amp;lt;&amp;lt; &quot;String 1: &quot; &amp;lt;&amp;lt; str1 &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;String 2: &quot; &amp;lt;&amp;lt; str2 &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Empty String: '&quot; &amp;lt;&amp;lt; emptyStr &amp;lt;&amp;lt; &quot;'&quot; &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;String 1: Hello, 
String 2: std::string!
Empty String: ''&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3.2 Length of a&amp;nbsp;String&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can use the&amp;nbsp;.length() or&amp;nbsp;.size() methods to find the length of a string.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
using namespace std;

int main() {
    string str = &quot;Hello, World!&quot;;
    cout &amp;lt;&amp;lt; &quot;String: &quot; &amp;lt;&amp;lt; str &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Length: &quot; &amp;lt;&amp;lt; str.length() &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;makefile&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;String: Hello, World!
Length: 13&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3.3 String Concatenation&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Strings can be concatenated using the + operator.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
using namespace std;

int main() {
    string str1 = &quot;C++ &quot;;
    string str2 = &quot;is fun!&quot;;
    string result = str1 + str2;

    cout &amp;lt;&amp;lt; &quot;Concatenated String: &quot; &amp;lt;&amp;lt; result &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;kotlin&quot; data-code-block-lang=&quot;kotlin&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Concatenated String: C++ is fun!&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3.4 Modifying Strings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can modify std::string easily with various operations.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
using namespace std;

int main() {
    string str = &quot;Hello, C++!&quot;;
    str[7] = 'W'; // Replace 'C' with 'W'
    str.append(&quot; Strings are cool!&quot;); // Append to the string

    cout &amp;lt;&amp;lt; &quot;Modified String: &quot; &amp;lt;&amp;lt; str &amp;lt;&amp;lt; endl;

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;armasm&quot; data-code-block-lang=&quot;javascript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Modified String: Hello, W++! Strings are cool!&lt;/code&gt;&lt;/pre&gt;
&lt;pre class=&quot;&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3.5 Comparing Strings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;You can compare two strings using relational operators.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
using namespace std;

int main() {
    string str1 = &quot;Apple&quot;;
    string str2 = &quot;Banana&quot;;

    if (str1 &amp;lt; str2) {
        cout &amp;lt;&amp;lt; str1 &amp;lt;&amp;lt; &quot; comes before &quot; &amp;lt;&amp;lt; str2 &amp;lt;&amp;lt; &quot; alphabetically.&quot; &amp;lt;&amp;lt; endl;
    } else {
        cout &amp;lt;&amp;lt; str1 &amp;lt;&amp;lt; &quot; comes after &quot; &amp;lt;&amp;lt; str2 &amp;lt;&amp;lt; &quot; alphabetically.&quot; &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;armasm&quot; data-code-block-lang=&quot;typescript&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Apple comes before Banana alphabetically.&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3.6 Finding Substrings&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The find() method locates a substring within a string.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this example, we are using the &lt;b&gt;find()&lt;/b&gt; method to locate a substring within a string.&lt;/p&gt;
&lt;pre class=&quot;arduino&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
using namespace std;

int main() {
    string str = &quot;C++ programming is fun!&quot;;
    size_t position = str.find(&quot;programming&quot;);

    if (position != string::npos) {
        cout &amp;lt;&amp;lt; &quot;'programming' found at position: &quot; &amp;lt;&amp;lt; position &amp;lt;&amp;lt; endl;
    } else {
        cout &amp;lt;&amp;lt; &quot;'programming' not found!&quot; &amp;lt;&amp;lt; endl;
    }

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;str.find(&quot;programming&quot;)&lt;/b&gt; searches for the first occurrence of the substring &quot;programming&quot; in the string str.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;string::npos&lt;/b&gt; is a constant in the C++ Standard Library, representing an invalid position.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;-The function &lt;b&gt;returns the index&lt;/b&gt; (position) where the substring begins in the string, or it returns &lt;b&gt;string::npos&lt;/b&gt; if the substring is not found.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;If find() does not find the substring, it returns string::npos, which is typically a very large number (usually -1 as an unsigned integer).&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;position&amp;nbsp;!= string::npos&lt;/b&gt; checks if the substring was found. If it wasn't found, the value of position will be string::npos.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&lt;b&gt;size_t position&lt;/b&gt; stores the result. The type size_t is an unsigned integer type, which is used for sizes and positions in C++.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;If the substring is found, the position where it starts is printed. The position is 4 in this case because the substring &quot;programming&quot; begins at index 4 of the string &quot;C++ programming is fun!&quot;.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;xquery&quot; data-code-block-lang=&quot;vbnet&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;'programming' found at position: 4&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;&amp;nbsp;&lt;/h3&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this tutorial, we explored:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;C-style strings&lt;/b&gt; and their limitations.&lt;/li&gt;
&lt;li&gt;The versatile &lt;b&gt;std::string&lt;/b&gt; class, including common methods like&amp;nbsp;.length(), concatenation, and substring searching.&lt;/li&gt;
&lt;li&gt;The fact that uninitialized std::string variables are &lt;b&gt;blank by default&lt;/b&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;For more advanced string manipulation functions, refer to the C++ String Documentation.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>c 스타일 문자열</category>
      <category>C++</category>
      <category>c++ 문자열</category>
      <category>c++ 튜토리얼</category>
      <category>C++ 프로그래밍</category>
      <category>std::string</category>
      <category>문자열 처리</category>
      <category>문자열 함수</category>
      <category>소프트웨어 개발</category>
      <category>프로그래밍 기초</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/17</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp004Introduction-to-Strings#entry17comment</comments>
      <pubDate>Wed, 1 Jan 2025 16:20:14 +0900</pubDate>
    </item>
    <item>
      <title>cpp_004_Introduction to Math Functions</title>
      <link>https://codeaddict.tistory.com/entry/cpp003Introduction-to-Math-Functions</link>
      <description>&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;C++ provides a wide range of math functions to perform calculations efficiently.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. Basic Arithmetic Operations&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;C++ supports standard arithmetic operations such as addition, subtraction, multiplication, and division.&amp;nbsp;&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
using namespace std;

int main() {
    int a = 10, b = 3;
    cout &amp;lt;&amp;lt; &quot;Addition: &quot; &amp;lt;&amp;lt; a + b &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Subtraction: &quot; &amp;lt;&amp;lt; a - b &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Multiplication: &quot; &amp;lt;&amp;lt; a * b &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Division: &quot; &amp;lt;&amp;lt; a / b &amp;lt;&amp;lt; endl;  // Integer division
    cout &amp;lt;&amp;lt; &quot;Modulus: &quot; &amp;lt;&amp;lt; a % b &amp;lt;&amp;lt; endl;   // Remainder
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;makefile&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Division&lt;/b&gt;: Since a and b are integers, the division result is truncated to an integer.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Modulus&lt;/b&gt;: The % operator gives the remainder of the division (10 divided by 3 leaves a remainder of 1).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Division&lt;/b&gt;: Since a and b are integers, the division result is truncated to an integer.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Modulus&lt;/b&gt;: The % operator gives the remainder of the division (10 divided by 3 leaves a remainder of 1).&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Trigonometric Functions&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Trigonometric functions like sin, cos, and tan are used for angle calculations. M_PI (&amp;pi;) is a predefined constant in &amp;lt;cmath&amp;gt;.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cmath&amp;gt;
using namespace std;

int main() {
    double angle = M_PI / 6;  // 30 degrees in radians
    cout &amp;lt;&amp;lt; &quot;sin(30&amp;deg;): &quot; &amp;lt;&amp;lt; sin(angle) &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;cos(30&amp;deg;): &quot; &amp;lt;&amp;lt; cos(angle) &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;tan(30&amp;deg;): &quot; &amp;lt;&amp;lt; tan(angle) &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;stylus&quot; data-code-block-lang=&quot;scss&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;sin(30&amp;deg;): 0.5
cos(30&amp;deg;): 0.866025
tan(30&amp;deg;): 0.57735&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Input&lt;/b&gt;: The angle is given in radians (not degrees). M_PI/6 corresponds to 30&amp;deg;.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Outputs&lt;/b&gt;: These are the standard trigonometric values for 30&amp;deg;:&lt;/li&gt;
&lt;li&gt;sin(30&amp;deg;) = 0.5&lt;/li&gt;
&lt;li&gt;cos(30&amp;deg;) &amp;asymp; 0.866025&lt;/li&gt;
&lt;li&gt;tan(30&amp;deg;) &amp;asymp; 0.57735&lt;/li&gt;
&lt;li&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Explanation of&amp;nbsp;M_PI&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;M_PI is a predefined constant in &amp;lt;cmath&amp;gt; that represents the value of &amp;pi; (pi) in mathematics. Its approximate value is 3.141592653589793. If M_PI is not available in some environments, you can define it manually:&lt;/p&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#define M_PI 3.141592653589793&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;4. Square Root and&amp;nbsp;Power&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The sqrt function calculates the square root, and pow calculates the power of a number.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cmath&amp;gt;
using namespace std;

int main() {
    cout &amp;lt;&amp;lt; &quot;Square root of 25: &quot; &amp;lt;&amp;lt; sqrt(25) &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;2^5: &quot; &amp;lt;&amp;lt; pow(2, 5) &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;makefile&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Square root of 25: 5
2^5: 32&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Square root&lt;/b&gt;: sqrt(25) returns 5 because 5&amp;times;5=25.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Power&lt;/b&gt;: pow(2, 5) returns 32 because 2^5 =2&amp;times;2&amp;times;2&amp;times;2&amp;times;2.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;5. Rounding Functions&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Functions like ceil, floor, round, and trunc handle decimal numbers differently.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cmath&amp;gt;
using namespace std;

int main() {
    double num = 7.65;
    cout &amp;lt;&amp;lt; &quot;Ceil: &quot; &amp;lt;&amp;lt; ceil(num) &amp;lt;&amp;lt; endl;   // Rounds up
    cout &amp;lt;&amp;lt; &quot;Floor: &quot; &amp;lt;&amp;lt; floor(num) &amp;lt;&amp;lt; endl; // Rounds down
    cout &amp;lt;&amp;lt; &quot;Round: &quot; &amp;lt;&amp;lt; round(num) &amp;lt;&amp;lt; endl; // Nearest integer
    cout &amp;lt;&amp;lt; &quot;Truncate: &quot; &amp;lt;&amp;lt; trunc(num) &amp;lt;&amp;lt; endl; // Removes fractional part
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;makefile&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Ceil: 8
Floor: 7
Round: 8
Truncate: 7&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;ceil&lt;/b&gt;: Always rounds up (7.65 &amp;rarr; 8).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;floor&lt;/b&gt;: Always rounds down (7.65 &amp;rarr; 7).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;round&lt;/b&gt;: Rounds to the nearest integer (7.65 &amp;rarr; 8).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;trunc&lt;/b&gt;: Removes the fractional part without rounding (7.65 &amp;rarr; 7).&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;6. Min and&amp;nbsp;Max&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The fmin and fmax functions find the smallest and largest of two numbers.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cmath&amp;gt;
using namespace std;

int main() {
    double x = 5.7, y = 8.2;
    cout &amp;lt;&amp;lt; &quot;Minimum: &quot; &amp;lt;&amp;lt; fmin(x, y) &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Maximum: &quot; &amp;lt;&amp;lt; fmax(x, y) &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;makefile&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Minimum: 5.7
Maximum: 8.2&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;fmin&lt;/b&gt;: Returns the smaller value.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;fmax&lt;/b&gt;: Returns the larger value.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;7. Modulus and Remainder&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The fmod function calculates the floating-point remainder, while remainder gives the remainder closest to zero.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cmath&amp;gt;
using namespace std;

int main() {
    double num1 = 8.75, num2 = 3.4;
    cout &amp;lt;&amp;lt; &quot;fmod(8.75, 3.4): &quot; &amp;lt;&amp;lt; fmod(num1, num2) &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;remainder(8.75, 3.4): &quot; &amp;lt;&amp;lt; remainder(num1, num2) &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;angelscript&quot; data-code-block-lang=&quot;scss&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;fmod(8.75, 3.4): 1.95
remainder(8.75, 3.4): -1.45&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;fmod&lt;/b&gt;: Computes the remainder after division (8.75 - (2 * 3.4) = 1.95).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;remainder&lt;/b&gt;: Returns the remainder closest to zero (-1.45). remainder(x,y)=x&amp;minus;(nearest multiple of y)&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;&lt;hr data-ke-style=&quot;style1&quot; /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;8. Infinity and&amp;nbsp;NaN&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;INFINITY represents positive infinity, and NaN (Not a Number) represents undefined results.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Code Example:&lt;/h3&gt;
&lt;pre class=&quot;cpp&quot; data-code-block-lang=&quot;cpp&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cmath&amp;gt;
using namespace std;

int main() {
    cout &amp;lt;&amp;lt; &quot;Positive Infinity: &quot; &amp;lt;&amp;lt; INFINITY &amp;lt;&amp;lt; endl;
    cout &amp;lt;&amp;lt; &quot;Negative Infinity: &quot; &amp;lt;&amp;lt; -INFINITY &amp;lt;&amp;lt; endl;

    double invalid = 0.0 / 0.0;
    cout &amp;lt;&amp;lt; &quot;NaN: &quot; &amp;lt;&amp;lt; invalid &amp;lt;&amp;lt; endl;
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Output:&lt;/h3&gt;
&lt;pre class=&quot;gams&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;Positive Infinity: inf
Negative Infinity: -inf
NaN: nan&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Explanation:&lt;/h3&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;INFINITY&lt;/b&gt;: Represents values that exceed the range of floating-point numbers.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;NaN&lt;/b&gt;: Results from undefined operations (e.g., dividing 0 by 0).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;The functions we covered in this tutorial (like sqrt, pow, fmod, remainder, ceil, floor, etc.) are all part of the &lt;b&gt;C++ Math Library&lt;/b&gt; provided in the &amp;lt;cmath&amp;gt; header. These functions help solve common mathematical problems efficiently.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;However, the &amp;lt;cmath&amp;gt; library includes many other powerful functions that were not covered here, such as:&lt;/p&gt;
&lt;ul style=&quot;list-style-type: disc;&quot; data-ke-list-type=&quot;disc&quot;&gt;
&lt;li&gt;&lt;b&gt;Hyperbolic functions&lt;/b&gt;: sinh, cosh, tanh, etc.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Exponential and logarithmic functions&lt;/b&gt;: exp, log, log10, etc.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Angle conversion&lt;/b&gt;: degrees, radians (available in C++20).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;More rounding functions&lt;/b&gt;: nearbyint, copysign, etc.&lt;/li&gt;
&lt;/ul&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;For a complete list of all mathematical functions available in &amp;lt;cmath&amp;gt;, you can refer to the official documentation:&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;</description>
      <category>C++ Beginner</category>
      <category>C++</category>
      <category>c++ 수학 함수</category>
      <category>c++ 수학 함수 사용법</category>
      <category>c++ 예제 코드</category>
      <category>math 라이브러리</category>
      <category>수학 연산</category>
      <category>수학 함수 예제</category>
      <category>코딩 입문</category>
      <category>프로그래밍 기초</category>
      <category>프로그래밍 초보자</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/16</guid>
      <comments>https://codeaddict.tistory.com/entry/cpp003Introduction-to-Math-Functions#entry16comment</comments>
      <pubDate>Wed, 1 Jan 2025 15:24:18 +0900</pubDate>
    </item>
    <item>
      <title>Python Intermediate_004_ Guide to PyYAML</title>
      <link>https://codeaddict.tistory.com/entry/Python-Intermediate004-Guide-to-PyYAML</link>
      <description>&lt;h3 data-ke-size=&quot;size23&quot;&gt;Introduction&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;When dealing with configuration files or structured data, YAML (short for &amp;ldquo;YAML Ain&amp;rsquo;t Markup Language&amp;rdquo;) is a popular format due to its simplicity and readability. YAML organizes data in a human-readable manner with minimal syntax, using indentation and symbols like&amp;nbsp;: for key-value pairs, - for lists, and nesting for hierarchy. In Python, the PyYAML library allows seamless interaction with YAML files for reading and writing structured data.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;In this blog post, we will walk through three examples, starting from simple to advanced, showcasing how to read from and write to YAML files using PyYAML. Each example will include clear explanations of the YAML structure and the corresponding Python code.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Prerequisites&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Before diving in, ensure you have installed PyYAML. Use the following command to install it via pip:&lt;/p&gt;
&lt;pre class=&quot;cmake&quot; data-code-block-mode=&quot;0&quot;&gt;&lt;code&gt;pip install pyyaml&lt;/code&gt;&lt;/pre&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;1. Example1: Reading and Writing a Flat YAML&amp;nbsp;File&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Create a YAML&amp;nbsp;File&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Create a file named user.yaml in the same directory as your Python script and add the following content:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;vbnet&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;name: Alice
age: 30
is_developer: true&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code: Reading and&amp;nbsp;Writing&lt;/h4&gt;
&lt;pre class=&quot;sql&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;import yaml

# Reading from a YAML file
with open('user.yaml', 'r') as file:
    user_data = yaml.safe_load(file)

print(&quot;Loaded YAML Data:&quot;, user_data)  # Output: {'name': 'Alice', 'age': 30, 'is_developer': True}

# Writing back to a new YAML file
updated_data = {
    'name': 'Alice',
    'age': 31,  # Update the age
    'is_developer': True
}

with open('updated_user.yaml', 'w') as file:
    yaml.dump(updated_data, file)
print(&quot;Updated YAML saved to 'updated_user.yaml'&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Reading&lt;/b&gt;: The yaml.safe_load() function parses the user.yaml file into a Python dictionary.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Writing&lt;/b&gt;: The yaml.dump() function serializes the updated dictionary back into a YAML file.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This approach is ideal for flat YAML files without nested structures.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;2. Example2: Handling Nested YAML&amp;nbsp;Data&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Create a YAML&amp;nbsp;File&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Create a file named config.yaml and add the following content:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;server:
  host: localhost
  port: 8000
  debug: true
database:
  name: app_db
  user: admin
  password: secret&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code: Reading and&amp;nbsp;Writing&lt;/h4&gt;
&lt;pre class=&quot;routeros&quot; data-code-block-lang=&quot;python&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;import yaml

# Reading nested YAML data
with open('config.yaml', 'r') as file:
    config = yaml.safe_load(file)

print(&quot;Database Config:&quot;, config['database'])  # Output: {'name': 'app_db', 'user': 'admin', 'password': 'secret'}

# Modifying and writing nested YAML data
config['server']['debug'] = False  # Disable debug mode
config['database']['password'] = 'new_secret'  # Update password

with open('updated_config.yaml', 'w') as file:
    yaml.dump(config, file)
print(&quot;Updated YAML saved to 'updated_config.yaml'&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Reading&lt;/b&gt;: Nested YAML structures are directly converted into Python dictionaries containing other dictionaries. Access nested elements using keys.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Modifying&lt;/b&gt;: You can update nested keys like config['server']['debug'] to change specific values.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Writing&lt;/b&gt;: The modified data is written back into a YAML file, preserving the nested structure.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This method is perfect for hierarchical configurations like server settings or application environments.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;3. Example3: Working with Lists in&amp;nbsp;YAML&lt;/h3&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;YAML Context&lt;/h4&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Now, consider a YAML file named employees.yaml that includes a list of employees:&lt;/p&gt;
&lt;pre class=&quot;yaml&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;1&quot;&gt;&lt;code&gt;employees:
  - name: John Doe
    age: 28
    skills:
      - Python
      - Django
  - name: Jane Smith
    age: 35
    skills:
      - JavaScript
      - React&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Code: Reading and&amp;nbsp;Writing&lt;/h4&gt;
&lt;pre class=&quot;python&quot; data-code-block-lang=&quot;yaml&quot; data-code-block-mode=&quot;2&quot;&gt;&lt;code&gt;import yaml

# Reading YAML with lists
with open('employees.yaml', 'r') as file:
    employees_data = yaml.safe_load(file)

for employee in employees_data['employees']:
    print(f&quot;Employee: {employee['name']}, Skills: {', '.join(employee['skills'])}&quot;)

# Adding a new employee to the list
new_employee = {
    'name': 'Alice Green',
    'age': 30,
    'skills': ['Flask', 'SQLAlchemy']
}
employees_data['employees'].append(new_employee)

with open('updated_employees.yaml', 'w') as file:
    yaml.dump(employees_data, file)
print(&quot;Updated YAML saved to 'updated_employees.yaml'&quot;)&lt;/code&gt;&lt;/pre&gt;
&lt;h4 data-ke-size=&quot;size20&quot;&gt;Explanation&lt;/h4&gt;
&lt;ol style=&quot;list-style-type: decimal;&quot; data-ke-list-type=&quot;decimal&quot;&gt;
&lt;li&gt;&lt;b&gt;Reading&lt;/b&gt;: The yaml.safe_load() function reads lists within YAML files as Python lists, allowing iteration.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Processing&lt;/b&gt;: Each employee is processed individually, demonstrating how to access nested data within lists.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Writing&lt;/b&gt;: A new employee is appended to the employees list, and the updated data is saved back into a YAML file.&lt;/li&gt;
&lt;/ol&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;This approach is particularly useful for datasets with repetitive structures, such as employee records, product catalogs, or inventory lists.&lt;/p&gt;
&lt;h3 data-ke-size=&quot;size23&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;PyYAML simplifies working with YAML files, whether you&amp;rsquo;re dealing with flat key-value pairs, nested configurations, or complex lists. By understanding how to read, modify, and write YAML files, you can leverage YAML&amp;rsquo;s human-readable format for configurations, data storage, or application settings.&lt;/p&gt;
&lt;p data-ke-size=&quot;size16&quot;&gt;Explore PyYAML in your projects to create cleaner, more maintainable configurations &amp;mdash; and let YAML handle the structure for you!&lt;/p&gt;</description>
      <category>Python  Intermediate and Advanced</category>
      <author>codeaddict</author>
      <guid isPermaLink="true">https://codeaddict.tistory.com/15</guid>
      <comments>https://codeaddict.tistory.com/entry/Python-Intermediate004-Guide-to-PyYAML#entry15comment</comments>
      <pubDate>Mon, 30 Dec 2024 22:16:20 +0900</pubDate>
    </item>
  </channel>
</rss>