[태그:] Productivity Tools

English articles about tools that improve personal or team productivity.

  • Python Beginner Lesson 12: Reading and Writing Files and CSV Basics

    In Python Beginner Lesson 12, we cover file handling and CSV in detail at a beginner-friendly level. The final goal of this lesson is to read and write text and CSV files while saving program results. Instead of stopping at copying code, we also check why this syntax is used and where beginners often make mistakes.

    When a program ends, values in memory disappear. By learning file handling, you can save results and read them again in the next run. Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: file handling and CSV
    • Today’s goal: read and write text and CSV files while saving program results
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 12: Reading and Writing Files and CSV Basics - File input and output lets you save data outside a program and read it again during the next run.
    File input and output lets you save data outside a program and read it again during the next run.

    When learning file handling and CSV, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • open() is a function that opens a file.
    • Using with automatically and safely closes the file.
    • CSV is a simple format that stores table data as lines and commas.
    • encoding is especially important when handling Korean text or any non-ASCII text.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    Read modeA mode for reading file contents. Usually r is used.
    Write modeA mode for writing new contents to a file. Usually w is used.
    CSVComma-Separated Values: table data separated by commas

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 12: Reading and Writing Files and CSV Basics - CSV is a good format for practicing how to save and read data arranged in rows and columns.
    CSV is a good format for practicing how to save and read data arranged in rows and columns.

    CSV is a good format for practicing how to save and read data arranged in rows and columns.

    import csv
    
    rows = [["Name", "Attendance"], ["Minsu", "O"], ["Jiyoung", "X"]]
    with open("attendance.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerows(rows)
    
    with open("attendance.csv", "r", encoding="utf-8") as f:
        reader = csv.reader(f)
        for row in reader:
            print(row)

    Understand the Code Line by Line

    • The csv module is imported.
    • The attendance.csv file is opened in write mode.
    • writerows() saves several rows at once.
    • The file is opened again in read mode, and each row is printed.

    At this stage, the important thing is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditionals, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code ran successfully, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After each change, always save and run the code again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether it becomes a friendlier explanation for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    FileNotFoundErrorThis is a common beginner-level problem.It occurs when the file you want to read does not exist or the path is wrong.
    Broken text encodingThis is a common beginner-level problem.Try specifying encoding=”utf-8″.
    Blank lines appearThis is a common beginner-level problem.In CSV writing, specifying newline=”” can reduce line-break problems.

    When an error appears, first look at the last line of the error message. Then check the file name and line number. Most beginner errors come from parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Save a memo as a text file.
    • Save names, scores, and pass/fail status in a CSV file.
    • Add exception handling that prints a guide message when the file does not exist.

    When solving practice problems, do not search for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    File handling and csv does not end with a small example. It keeps appearing in business automation when organizing files, in data analysis when reading table data, and in web API work when handling response values. The beginner syntax you learn now also becomes the basic language for using tools such as pandas, requests, and FastAPI later.

    An Analogy for Beginners

    When you first see file handling and CSV, syntax symbols may catch your eye before anything else. But if you see syntax only as symbols, you get tired quickly. A better method is to understand it by role. The core of this lesson is read and write text and CSV files while saving program results. In other words, you are practicing how to decide what task to give Python and write the processing order as code.

    Think of a cooking recipe. You prepare ingredients, process them in order, control the heat, and finally put the result on a plate. Python code is similar. You prepare the necessary values, process them in a defined order, and print or save the result. For beginners, developing this sense of order is most important.

    Follow the Execution Flow Visually

    Before running code, divide your thinking into the three columns below. This habit helps not only with simple examples but also later when you build longer projects.

    SectionCheck questionMeaning in this lesson
    InputWhat value does the program receive first?Values entered by the user or written in advance in the file handling and CSV example.
    ProcessingWhat calculation or decision is made?The part Python runs in order to achieve: read and write text and CSV files while saving program results.
    OutputWhat result does the user check?This may be a print result, saved file, generated graph, or changed data.

    Simply filling in this table yourself improves your code-reading ability. Beginners often struggle because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error occurs, do not delete code at random. If you check in the following order, you can find most beginner errors on your own.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check whether parentheses, quotation marks, colons, and commas match.
    • Check whether the variable name is exactly the same as the name defined earlier.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look less scary and more like clues. Python skill grows more from reading and fixing errors than from avoiding errors.

    Application Direction: Grow Today’s Lesson a Little Further

    Once you are comfortable with this example, keep file handling and CSV as the base and change one thing among the input value, output message, storage method, or repeat count. You do not need to build a completely new example. At the beginner stage, many small variations are best.

    • Change the variable names in the example to make them more meaningful.
    • Refine the output sentence so it reads like a guide shown to a real user.
    • Intentionally test what happens when invalid input is entered.
    • Explain the code with comments and check what you understand.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why file handling and CSV is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    FAQ

    Can I follow Python file handling and CSV even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    The next lesson is Python Beginner Lesson 13: Errors and Exception Handling with try except. Based on the flow you practiced here, you will explore errors and exception handling in more detail.

    References

    Original Korean article: https://www.thinknote.co.kr/python-beginner-12-file-csv/

  • Python Beginner Lesson 13: Errors and Exception Handling with try except

    In Python Beginner Lesson 13, we cover errors and exception handling in detail at a beginner-friendly level. The final goal of this lesson is to handle expected errors so the program does not suddenly stop. Instead of stopping at copying code, we also check why this syntax is used and where beginners often make mistakes.

    Beginners often panic when an error appears, but an error message is a clue for finding the problem. When you learn exception handling, you can deal with wrong input or file problems more safely. Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: errors and exception handling
    • Today’s goal: handle expected errors so the program does not suddenly stop
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 13: Errors and Exception Handling with try except - Exception handling is a structure that prepares a recovery path so a program does not immediately stop even when an error occurs.
    Exception handling is a structure that prepares a recovery path so a program does not immediately stop even when an error occurs.

    When learning errors and exception handling, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • A syntax error means the code format is wrong before execution.
    • An exception means an unexpected problem occurred during execution.
    • Write code to try inside try, and write what to do on error inside except.
    • finally can contain code that runs regardless of whether an error occurred.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    SyntaxErrorAn error that occurs when the syntax itself is invalid
    ValueErrorAn error that occurs when the shape of a value differs from what is expected
    Exception handlingA way to control program flow in preparation for error situations

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 13: Errors and Exception Handling with try except - Practice that filters wrong input and asks again shows the need for try except most clearly.
    Practice that filters wrong input and asks again shows the need for try except most clearly.

    Practice that filters wrong input and asks again shows the need for try except most clearly.

    def get_number():
        while True:
            try:
                value = int(input("Enter a number: "))
                return value
            except ValueError:
                print("Please enter numbers only.")
    
    number = get_number()
    print(f"Twice the number you entered is {number * 2}.")

    Understand the Code Line by Line

    • while True repeats until a valid value is entered.
    • Inside try, the input value is converted to an integer.
    • If integer conversion succeeds, return ends the function.
    • If ValueError occurs, a guide message is printed and input is requested again.

    The important point at this stage is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditions, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code runs, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After changing something, always save and run the file again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether the explanation becomes friendlier for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    Overusing except ExceptionThis is a common beginner-stage problem.If you hide every error, it becomes hard to find the real problem.
    Ignoring error messagesThis is a common beginner-stage problem.First check the error type and line number on the last line.
    Missing loop exitThis is a common beginner-stage problem.Without return or break after valid input, the loop may continue forever.

    When an error occurs, first look at the last line of the error message. Then check the file name and line number. Most beginner errors happen around parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Print a guide message when a user tries to divide by zero.
    • When reading a missing file, handle it by creating a default file.
    • Use multiple except blocks to print different messages for different errors.

    When solving practice problems, do not look for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    Errors and exception handling does not end with a small example. It appears again and again when organizing files in business automation, reading table data in data analysis, and handling response values in web APIs. The beginner syntax you learn now also becomes the basic language you use later with tools such as pandas, requests, and FastAPI.

    A Beginner-Friendly Analogy

    When you first see errors and exception handling, syntax symbols may catch your eye first. But if you look at syntax only as symbols, you will quickly get tired. A better method is to understand it by role. The core of this lesson is to handle expected errors so the program does not suddenly stop. In other words, you are practicing how to decide what job to give Python and write the order of that job as code.

    Think of a cooking recipe. You prepare ingredients, handle them in order, control the heat, and finally serve the dish. Python code is similar. You prepare the needed values, process them in a defined order, and print or save the result. For beginners, building this sense of order is the most important part.

    Follow the Execution Flow Visually

    Before running code, think in the following three boxes. This habit helps not only with simple examples but also later when you build longer projects.

    SectionQuestion to checkMeaning in this lesson
    InputWhat value does the program receive first?Values the user enters or values written in advance in the errors and exception handling example.
    ProcessingWhat calculation or decision happens?The part Python runs in order to achieve the goal: handle expected errors so the program does not suddenly stop.
    OutputWhat result does the user check?This may be a print result, saved file, created graph, or changed data.

    Simply filling in this table yourself improves code comprehension. Beginners struggle partly because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error appears, do not delete code at random. If you check in the order below, you can find most beginner errors yourself.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check parentheses, quotation marks, colons, and commas.
    • Check whether the variable name exactly matches the name defined above.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look like clues instead of something scary. Python skill grows more from reading and fixing errors than from avoiding them completely.

    Application Ideas: Grow Today’s Lesson a Little

    Once this example feels familiar, keep the errors and exception handling example and change one thing: an input value, an output sentence, a saving method, or a repeat count. You do not need to make a completely new example. At the beginner stage, many small variations are the best practice.

    • Change variable names in the example to make them more meaningful.
    • Refine output sentences so they read like guidance shown to a real user.
    • Deliberately check what happens when invalid input is entered.
    • Explain the code with comments to check your own understanding.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why errors and exception handling is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    • Python Beginner 20-Lesson Complete Guide
    • Previous lesson: Python Beginner Lesson 12: Reading and Writing Files and CSV Basics
    • Next lesson: Python Beginner Lesson 14: Understand Classes and Objects Easily
    • Business automation article collection

    FAQ

    Can I follow Python exception handling even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    The next lesson is Python Beginner Lesson 14: Understand Classes and Objects Easily. Based on the flow you practiced here, you will explore classes and objects in more detail.

    References

    • Python Official Tutorial
    • Python Official Tutorial: Control Flow Tools
    • Python Official Tutorial: Data Structures
    • Python Official Tutorial: Modules
    • Python Official Tutorial: Input and Output

    Original Korean article: https://www.thinknote.co.kr/python-beginner-13-exceptions/

  • Python Beginner Lesson 14: Understand Classes and Objects Easily

    In Python Beginner Lesson 14, we cover classes and objects in detail at a beginner-friendly level. The final goal of this lesson is to think of related data and behavior as one structure. Instead of stopping at copying code, we also check why this syntax is used and where beginners often make mistakes.

    You do not need to memorize object-oriented programming deeply from the start. Still, if you learn the feeling of bundling data with the features that handle it, larger programs become easier to understand. Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: classes and objects
    • Today’s goal: think of related data and behavior as one structure
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 14: Understand Classes and Objects Easily - A class is a blueprint for creating multiple objects, and an object is an actual bundle of data made from that blueprint.
    A class is a blueprint for creating multiple objects, and an object is an actual bundle of data made from that blueprint.

    When learning classes and objects, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • A class is a blueprint.
    • An object is actual data created from a class.
    • An attribute is a value an object has.
    • A method is an action an object can perform.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    classSyntax for defining a new data structure
    selfThe name that points to the current object itself
    __init__An initialization method that runs when an object is created

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 14: Understand Classes and Objects Easily - If you bundle attributes and actions together like a student card, the roles of classes and objects become clearer.
    If you bundle attributes and actions together like a student card, the roles of classes and objects become clearer.

    If you bundle attributes and actions together like a student card, the roles of classes and objects become clearer.

    class Student:
        def __init__(self, name, score):
            self.name = name
            self.score = score
    
        def is_passed(self):
            return self.score >= 60
    
        def introduce(self):
            result = "Passed" if self.is_passed() else "Try again"
            print(f"{self.name}: {self.score} points, {result}")
    
    student = Student("Minsu", 85)
    student.introduce()

    Understand the Code Line by Line

    • The Student class is a blueprint that represents student data.
    • __init__ receives name and score and saves them as object attributes.
    • is_passed() returns whether the student passed based on the score.
    • introduce() uses values in the object to print a sentence.

    The important point at this stage is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditions, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code runs, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After changing something, always save and run the file again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether the explanation becomes friendlier for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    Missing selfThis is a common beginner-stage problem.Inside a class, the first parameter of a method must be self.
    Confusing class and objectThis is a common beginner-stage problem.A class is a blueprint; an object is the data actually created from it.
    Missing initial valuesThis is a common beginner-stage problem.When creating an object, you must provide all values required by __init__.

    When an error occurs, first look at the last line of the error message. Then check the file name and line number. Most beginner errors happen around parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Create a Book class and store a title and author.
    • Create a Product class with a product name and price.
    • Add a method that changes the score.

    When solving practice problems, do not look for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    Classes and objects does not end with a small example. It appears again and again when organizing files in business automation, reading table data in data analysis, and handling response values in web APIs. The beginner syntax you learn now also becomes the basic language you use later with tools such as pandas, requests, and FastAPI.

    A Beginner-Friendly Analogy

    When you first see classes and objects, syntax symbols may catch your eye first. But if you look at syntax only as symbols, you will quickly get tired. A better method is to understand it by role. The core of this lesson is to think of related data and behavior as one structure. In other words, you are practicing how to decide what job to give Python and write the order of that job as code.

    Think of a cooking recipe. You prepare ingredients, handle them in order, control the heat, and finally serve the dish. Python code is similar. You prepare the needed values, process them in a defined order, and print or save the result. For beginners, building this sense of order is the most important part.

    Follow the Execution Flow Visually

    Before running code, think in the following three boxes. This habit helps not only with simple examples but also later when you build longer projects.

    SectionQuestion to checkMeaning in this lesson
    InputWhat value does the program receive first?Values the user enters or values written in advance in the classes and objects example.
    ProcessingWhat calculation or decision happens?The part Python runs in order to achieve the goal: think of related data and behavior as one structure.
    OutputWhat result does the user check?This may be a print result, saved file, created graph, or changed data.

    Simply filling in this table yourself improves code comprehension. Beginners struggle partly because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error appears, do not delete code at random. If you check in the order below, you can find most beginner errors yourself.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check parentheses, quotation marks, colons, and commas.
    • Check whether the variable name exactly matches the name defined above.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look like clues instead of something scary. Python skill grows more from reading and fixing errors than from avoiding them completely.

    Application Ideas: Grow Today’s Lesson a Little

    Once this example feels familiar, keep the classes and objects example and change one thing: an input value, an output sentence, a saving method, or a repeat count. You do not need to make a completely new example. At the beginner stage, many small variations are the best practice.

    • Change variable names in the example to make them more meaningful.
    • Refine output sentences so they read like guidance shown to a real user.
    • Deliberately check what happens when invalid input is entered.
    • Explain the code with comments to check your own understanding.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why classes and objects is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    • Python Beginner 20-Lesson Complete Guide
    • Previous lesson: Python Beginner Lesson 13: Errors and Exception Handling with try except
    • Next lesson: Python Beginner Lesson 15: Address Book Project Saved to a File
    • Business automation article collection

    FAQ

    Can I follow Python classes even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    The next lesson is Python Beginner Lesson 15: Address Book Project Saved to a File. Based on the flow you practiced here, you will explore an address book project in more detail.

    References

    • Python Official Tutorial
    • Python Official Tutorial: Control Flow Tools
    • Python Official Tutorial: Data Structures
    • Python Official Tutorial: Modules
    • Python Official Tutorial: Input and Output

    Original Korean article: https://www.thinknote.co.kr/python-beginner-14-class-object/

  • Python Beginner Lesson 15: Address Book Project Saved to a File

    In Python Beginner Lesson 15, we cover an address book project in detail at a beginner-friendly level. The final goal of this lesson is to connect adding, searching, saving, and loading contacts. Instead of stopping at copying code, we also check why this syntax is used and where beginners often make mistakes.

    In previous projects, data stayed only while the program was running. The address book project includes file saving, so you practice a structure closer to a real program. Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: an address book project
    • Today’s goal: connect adding, searching, saving, and loading contacts
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 15: Address Book Project Saved to a File - The address book project is a small-app practice for adding and finding contact data and saving it to a file.
    The address book project is a small-app practice for adding and finding contact data and saving it to a file.

    When learning an address book project, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • Address book data can store names as keys and phone numbers as values.
    • JSON is convenient for saving a dictionary structure to a file.
    • Exception handling is needed in case a file does not exist or is broken.
    • A project becomes easier when you think separately about the data structure, features, and saving method.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    JSONA data format that saves dictionaries and lists as text
    CRUDBasic data features such as creating, reading, updating, and deleting contacts
    PersistenceThe property that data remains after the program ends

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 15: Address Book Project Saved to a File - When you handle search and saving together, you can see how dictionaries, files, and JSON connect in a real program.
    When you handle search and saving together, you can see how dictionaries, files, and JSON connect in a real program.

    When you handle search and saving together, you can see how dictionaries, files, and JSON connect in a real program.

    import json
    from pathlib import Path
    
    FILE = Path("contacts.json")
    
    def load_contacts():
        if not FILE.exists():
            return {}
        with open(FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    
    def save_contacts(contacts):
        with open(FILE, "w", encoding="utf-8") as f:
            json.dump(contacts, f, ensure_ascii=False, indent=2)
    
    contacts = load_contacts()
    contacts["Minsu"] = "010-1111-2222"
    save_contacts(contacts)
    print(load_contacts())

    Understand the Code Line by Line

    • Use a Path object to set the save-file path.
    • If the file does not exist, return an empty dictionary.
    • json.load() reads file contents as a dictionary.
    • json.dump() saves a dictionary as a JSON file.

    The important point at this stage is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditions, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code runs, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After changing something, always save and run the file again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether the explanation becomes friendlier for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    JSONDecodeErrorThis is a common beginner-stage problem.It happens when the file contents are not in JSON format.
    Forgotten saveThis is a common beginner-stage problem.Check whether you called save_contacts() after changing the data.
    File path confusionThis is a common beginner-stage problem.Depending on the run location, the file may be created in a different folder.

    When an error occurs, first look at the last line of the error message. Then check the file name and line number. Most beginner errors happen around parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Add a contact search function.
    • Create a feature that edits a phone number.
    • Before deleting, receive input to confirm whether the user really wants to delete.

    When solving practice problems, do not look for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    An address book project does not end with a small example. It appears again and again when organizing files in business automation, reading table data in data analysis, and handling response values in web APIs. The beginner syntax you learn now also becomes the basic language you use later with tools such as pandas, requests, and FastAPI.

    A Beginner-Friendly Analogy

    When you first see an address book project, syntax symbols may catch your eye first. But if you look at syntax only as symbols, you will quickly get tired. A better method is to understand it by role. The core of this lesson is to connect adding, searching, saving, and loading contacts. In other words, you are practicing how to decide what job to give Python and write the order of that job as code.

    Think of a cooking recipe. You prepare ingredients, handle them in order, control the heat, and finally serve the dish. Python code is similar. You prepare the needed values, process them in a defined order, and print or save the result. For beginners, building this sense of order is the most important part.

    Follow the Execution Flow Visually

    Before running code, think in the following three boxes. This habit helps not only with simple examples but also later when you build longer projects.

    SectionQuestion to checkMeaning in this lesson
    InputWhat value does the program receive first?Values the user enters or values written in advance in the an address book project example.
    ProcessingWhat calculation or decision happens?The part Python runs in order to achieve the goal: connect adding, searching, saving, and loading contacts.
    OutputWhat result does the user check?This may be a print result, saved file, created graph, or changed data.

    Simply filling in this table yourself improves code comprehension. Beginners struggle partly because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error appears, do not delete code at random. If you check in the order below, you can find most beginner errors yourself.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check parentheses, quotation marks, colons, and commas.
    • Check whether the variable name exactly matches the name defined above.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look like clues instead of something scary. Python skill grows more from reading and fixing errors than from avoiding them completely.

    Application Ideas: Grow Today’s Lesson a Little

    Once this example feels familiar, keep the an address book project example and change one thing: an input value, an output sentence, a saving method, or a repeat count. You do not need to make a completely new example. At the beginner stage, many small variations are the best practice.

    • Change variable names in the example to make them more meaningful.
    • Refine output sentences so they read like guidance shown to a real user.
    • Deliberately check what happens when invalid input is entered.
    • Explain the code with comments to check your own understanding.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why an address book project is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    • Python Beginner 20-Lesson Complete Guide
    • Previous lesson: Python Beginner Lesson 14: Understand Classes and Objects Easily
    • Next lesson: Python Beginner Lesson 16: Work with Dates, Paths, and Patterns Using the Standard Library
    • Business automation article collection

    FAQ

    Can I follow Python address book even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    The next lesson is Python Beginner Lesson 16: Work with Dates, Paths, and Patterns Using the Standard Library. Based on the flow you practiced here, you will explore the standard library in more detail.

    References

    • Python Official Tutorial
    • Python Official Tutorial: Control Flow Tools
    • Python Official Tutorial: Data Structures
    • Python Official Tutorial: Modules
    • Python Official Tutorial: Input and Output

    Original Korean article: https://www.thinknote.co.kr/python-beginner-15-address-book-project/

  • Python Beginner Lesson 16: Work with Dates, Paths, and Patterns Using the Standard Library

    In Python Beginner Lesson 16, we cover the standard library in detail at a beginner-friendly level. The final goal of this lesson is to learn date, path, and pattern tools you can use without installation. Instead of stopping at copying code, we also check why this syntax is used and where beginners often make mistakes.

    Even without installing external packages, Python provides many tools by default. If you know the standard library, you can create simple automation right away. Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: the standard library
    • Today’s goal: learn date, path, and pattern tools you can use without installation
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 16: Work with Dates, Paths, and Patterns Using the Standard Library - The standard library is a toolbox that provides basic features such as dates, paths, and pattern searching without separate installation.
    The standard library is a toolbox that provides basic features such as dates, paths, and pattern searching without separate installation.

    When learning the standard library, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • datetime handles dates and times.
    • pathlib handles file and folder paths like objects.
    • re is a regular-expression tool for finding patterns in strings.
    • For beginners, it is enough to first learn the names of standard libraries and when to use them.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    datetimeA standard module for handling dates and times
    pathlibA standard module for handling file paths safely
    Regular expressionA way to express patterns for finding or replacing strings

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 16: Work with Dates, Paths, and Patterns Using the Standard Library - Creating a dated file and finding a pattern in a document helps you build practical intuition for the standard library.
    Creating a dated file and finding a pattern in a document helps you build practical intuition for the standard library.

    Creating a dated file and finding a pattern in a document helps you build practical intuition for the standard library.

    from datetime import date
    from pathlib import Path
    import re
    
    today = date.today().isoformat()
    folder = Path("reports")
    folder.mkdir(exist_ok=True)
    
    file_path = folder / f"report-{today}.txt"
    file_path.write_text("Today’s report", encoding="utf-8")
    
    text = "Order number: A-2026-0712"
    match = re.search(r"A-\d{4}-\d{4}", text)
    print(file_path)
    print(match.group() if match else "No pattern found")

    Understand the Code Line by Line

    • date.today() gets today’s date.
    • Path(“reports”) represents the reports folder.
    • mkdir(exist_ok=True) avoids an error even if the folder already exists.
    • re.search() finds a pattern in a string.

    The important point at this stage is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditions, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code runs, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After changing something, always save and run the file again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether the explanation becomes friendlier for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    Path separator problemThis is a common beginner-stage problem.Using pathlib instead of string paths reduces operating-system differences.
    Overusing regular expressionsThis is a common beginner-stage problem.For simple replacement, replace() is easier; for splitting, split() is easier.
    NoneType errorThis is a common beginner-stage problem.A re.search() result may be missing, so check whether match exists.

    When an error occurs, first look at the last line of the error message. Then check the file name and line number. Most beginner errors happen around parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Create a memo file that includes today’s date.
    • Automatically create a specific folder if it does not exist.
    • Find a string that looks like an email address in a sentence.

    When solving practice problems, do not look for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    The standard library does not end with a small example. It appears again and again when organizing files in business automation, reading table data in data analysis, and handling response values in web APIs. The beginner syntax you learn now also becomes the basic language you use later with tools such as pandas, requests, and FastAPI.

    A Beginner-Friendly Analogy

    When you first see the standard library, syntax symbols may catch your eye first. But if you look at syntax only as symbols, you will quickly get tired. A better method is to understand it by role. The core of this lesson is to learn date, path, and pattern tools you can use without installation. In other words, you are practicing how to decide what job to give Python and write the order of that job as code.

    Think of a cooking recipe. You prepare ingredients, handle them in order, control the heat, and finally serve the dish. Python code is similar. You prepare the needed values, process them in a defined order, and print or save the result. For beginners, building this sense of order is the most important part.

    Follow the Execution Flow Visually

    Before running code, think in the following three boxes. This habit helps not only with simple examples but also later when you build longer projects.

    SectionQuestion to checkMeaning in this lesson
    InputWhat value does the program receive first?Values the user enters or values written in advance in the the standard library example.
    ProcessingWhat calculation or decision happens?The part Python runs in order to achieve the goal: learn date, path, and pattern tools you can use without installation.
    OutputWhat result does the user check?This may be a print result, saved file, created graph, or changed data.

    Simply filling in this table yourself improves code comprehension. Beginners struggle partly because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error appears, do not delete code at random. If you check in the order below, you can find most beginner errors yourself.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check parentheses, quotation marks, colons, and commas.
    • Check whether the variable name exactly matches the name defined above.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look like clues instead of something scary. Python skill grows more from reading and fixing errors than from avoiding them completely.

    Application Ideas: Grow Today’s Lesson a Little

    Once this example feels familiar, keep the the standard library example and change one thing: an input value, an output sentence, a saving method, or a repeat count. You do not need to make a completely new example. At the beginner stage, many small variations are the best practice.

    • Change variable names in the example to make them more meaningful.
    • Refine output sentences so they read like guidance shown to a real user.
    • Deliberately check what happens when invalid input is entered.
    • Explain the code with comments to check your own understanding.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why the standard library is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    • Python Beginner 20-Lesson Complete Guide
    • Previous lesson: Python Beginner Lesson 15: Address Book Project Saved to a File
    • Next lesson: Python Beginner Lesson 17: Introduction to Folder and File Automation
    • Business automation article collection

    FAQ

    Can I follow Python standard library even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    The next lesson is Python Beginner Lesson 17: Introduction to Folder and File Automation. Based on the flow you practiced here, you will explore file automation in more detail.

    References

    • Python Official Tutorial
    • Python Official Tutorial: Control Flow Tools
    • Python Official Tutorial: Data Structures
    • Python Official Tutorial: Modules
    • Python Official Tutorial: Input and Output

    Original Korean article: https://www.thinknote.co.kr/python-beginner-16-standard-library/

  • Python Beginner Lesson 17: Introduction to Folder and File Automation

    In Python Beginner Lesson 17, we cover file automation in detail at a beginner-friendly level. The final goal of this lesson is to collect file information from a folder and turn it into a CSV report. Instead of stopping at copying code, we also check why this syntax is used and where beginners often make mistakes.

    Business automation does not start with something as grand as AI. Simply organizing a folder’s file list, classifying files by extension, and saving a report can already save time. Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: file automation
    • Today’s goal: collect file information from a folder and turn it into a CSV report
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 17: Introduction to Folder and File Automation - File automation organizes scattered files by rules and reduces repetitive checking work.
    File automation organizes scattered files by rules and reduces repetitive checking work.

    When learning file automation, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • Folder traversal means checking files inside a specific folder one by one.
    • Information such as file size, extension, and modified date is often used in automated reports.
    • When you first automate, it is safer to avoid changing original files and start with reading and report creation.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    iterdirA pathlib method that takes items from a folder one by one
    statA feature that gets information such as file size and modified time
    Report automationSaving repeated checking results as a table or file

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 17: Introduction to Folder and File Automation - When you scan a folder, collect file information, and save it as a report, you can immediately feel the effect of automation.
    When you scan a folder, collect file information, and save it as a report, you can immediately feel the effect of automation.

    When you scan a folder, collect file information, and save it as a report, you can immediately feel the effect of automation.

    from pathlib import Path
    import csv
    
    folder = Path(".")
    files = []
    for path in folder.iterdir():
        if path.is_file():
            files.append([path.name, path.suffix, path.stat().st_size])
    
    with open("file_report.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["File name", "Extension", "Size"])
        writer.writerows(files)
    
    print(f"Saved information for {len(files)} files.")

    Understand the Code Line by Line

    • Set the current folder with Path(“.”).
    • Use iterdir() to check each item in the folder.
    • Use is_file() to select files only.
    • Collect the file name, extension, and size in a list, then save them to CSV.

    The important point at this stage is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditions, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code runs, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After changing something, always save and run the file again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether the explanation becomes friendlier for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    PermissionErrorThis is a common beginner-stage problem.It happens when you access a file or folder without permission.
    Risk of changing originalsThis is a common beginner-stage problem.Use commands such as rename or unlink only after making a backup.
    Relative path confusionThis is a common beginner-stage problem.Check the current run location with print(Path.cwd()).

    When an error occurs, first look at the last line of the error message. Then check the file name and line number. Most beginner errors happen around parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Include only .txt files in the report.
    • Sort files by largest size first.
    • Look up and use rglob() if you want to include subfolders too.

    When solving practice problems, do not look for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    File automation does not end with a small example. It appears again and again when organizing files in business automation, reading table data in data analysis, and handling response values in web APIs. The beginner syntax you learn now also becomes the basic language you use later with tools such as pandas, requests, and FastAPI.

    A Beginner-Friendly Analogy

    When you first see file automation, syntax symbols may catch your eye first. But if you look at syntax only as symbols, you will quickly get tired. A better method is to understand it by role. The core of this lesson is to collect file information from a folder and turn it into a CSV report. In other words, you are practicing how to decide what job to give Python and write the order of that job as code.

    Think of a cooking recipe. You prepare ingredients, handle them in order, control the heat, and finally serve the dish. Python code is similar. You prepare the needed values, process them in a defined order, and print or save the result. For beginners, building this sense of order is the most important part.

    Follow the Execution Flow Visually

    Before running code, think in the following three boxes. This habit helps not only with simple examples but also later when you build longer projects.

    SectionQuestion to checkMeaning in this lesson
    InputWhat value does the program receive first?Values the user enters or values written in advance in the file automation example.
    ProcessingWhat calculation or decision happens?The part Python runs in order to achieve the goal: collect file information from a folder and turn it into a CSV report.
    OutputWhat result does the user check?This may be a print result, saved file, created graph, or changed data.

    Simply filling in this table yourself improves code comprehension. Beginners struggle partly because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error appears, do not delete code at random. If you check in the order below, you can find most beginner errors yourself.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check parentheses, quotation marks, colons, and commas.
    • Check whether the variable name exactly matches the name defined above.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look like clues instead of something scary. Python skill grows more from reading and fixing errors than from avoiding them completely.

    Application Ideas: Grow Today’s Lesson a Little

    Once this example feels familiar, keep the file automation example and change one thing: an input value, an output sentence, a saving method, or a repeat count. You do not need to make a completely new example. At the beginner stage, many small variations are the best practice.

    • Change variable names in the example to make them more meaningful.
    • Refine output sentences so they read like guidance shown to a real user.
    • Deliberately check what happens when invalid input is entered.
    • Explain the code with comments to check your own understanding.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why file automation is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    • Python Beginner 20-Lesson Complete Guide
    • Previous lesson: Python Beginner Lesson 16: Work with Dates, Paths, and Patterns Using the Standard Library
    • Next lesson: Python Beginner Lesson 18: A Taste of Data Analysis with pandas and matplotlib
    • Business automation article collection

    FAQ

    Can I follow Python automation even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    The next lesson is Python Beginner Lesson 18: A Taste of Data Analysis with pandas and matplotlib. Based on the flow you practiced here, you will explore a taste of data analysis in more detail.

    References

    • Python Official Tutorial
    • Python Official Tutorial: Control Flow Tools
    • Python Official Tutorial: Data Structures
    • Python Official Tutorial: Modules
    • Python Official Tutorial: Input and Output

    Original Korean article: https://www.thinknote.co.kr/python-beginner-17-file-automation/

  • Python Beginner Lesson 18: A Taste of Data Analysis with pandas and matplotlib

    In Python Beginner Lesson 18, we cover a taste of data analysis in detail at a beginner-friendly level. The final goal of this lesson is to read CSV data as a table, summarize it, and save it as a graph. Instead of stopping at copying code, we also check why this syntax is used and where beginners often make mistakes.

    One major reason many people learn Python is data analysis. At the beginner stage, it is more important to experience the flow of reading data, checking averages, and saving a graph than to study complex statistics. Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: a taste of data analysis
    • Today’s goal: read CSV data as a table, summarize it, and save it as a graph
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 18: A Taste of Data Analysis with pandas and matplotlib - pandas handles table data in a form that is easy to calculate, and matplotlib shows the result as a graph.
    pandas handles table data in a form that is easy to calculate, and matplotlib shows the result as a graph.

    When learning a taste of data analysis, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • pandas handles table data with a structure called a DataFrame.
    • matplotlib is a representative tool for drawing graphs.
    • External packages must be installed with pip install.
    • Analysis is more stable when you proceed in the order of reading, checking, summarizing, and visualizing.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    DataFramepandas data in a table shape with rows and columns
    VisualizationThe task of showing data as graphs or charts
    Virtual environmentA way to separate package installation spaces by project

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 18: A Taste of Data Analysis with pandas and matplotlib - If you summarize data and save it as a chart image, you can use the analysis result in other documents or reports.
    If you summarize data and save it as a chart image, you can use the analysis result in other documents or reports.

    If you summarize data and save it as a chart image, you can use the analysis result in other documents or reports.

    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = pd.DataFrame({
        "month": ["Jan", "Feb", "Mar"],
        "sales": [120, 150, 180]
    })
    
    print(data)
    print("Average sales:", data["sales"].mean())
    
    data.plot(kind="bar", x="month", y="sales", legend=False)
    plt.title("Monthly Sales")
    plt.tight_layout()
    plt.savefig("sales.png")

    Understand the Code Line by Line

    • pd.DataFrame creates a small table of data.
    • data[“sales”].mean() calculates the average sales value.
    • plot(kind=”bar”) draws a bar chart.
    • savefig() saves the graph as an image file.

    The important point at this stage is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditions, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code runs, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After changing something, always save and run the file again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether the explanation becomes friendlier for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    ModuleNotFoundErrorThis is a common beginner-stage problem.Install the packages with pip install pandas matplotlib.
    Broken Korean font renderingThis is a common beginner-stage problem.Font settings may be needed depending on the operating system.
    CSV encoding problemThis is a common beginner-stage problem.Use read_csv(…, encoding=”utf-8″) or cp949 depending on the situation.

    When an error occurs, first look at the last line of the error message. Then check the file name and line number. Most beginner errors happen around parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Create monthly visitor data and calculate the average.
    • Draw a line graph instead of a bar graph.
    • Change the example so it reads a CSV file with read_csv().

    When solving practice problems, do not look for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    A taste of data analysis does not end with a small example. It appears again and again when organizing files in business automation, reading table data in data analysis, and handling response values in web APIs. The beginner syntax you learn now also becomes the basic language you use later with tools such as pandas, requests, and FastAPI.

    A Beginner-Friendly Analogy

    When you first see a taste of data analysis, syntax symbols may catch your eye first. But if you look at syntax only as symbols, you will quickly get tired. A better method is to understand it by role. The core of this lesson is to read CSV data as a table, summarize it, and save it as a graph. In other words, you are practicing how to decide what job to give Python and write the order of that job as code.

    Think of a cooking recipe. You prepare ingredients, handle them in order, control the heat, and finally serve the dish. Python code is similar. You prepare the needed values, process them in a defined order, and print or save the result. For beginners, building this sense of order is the most important part.

    Follow the Execution Flow Visually

    Before running code, think in the following three boxes. This habit helps not only with simple examples but also later when you build longer projects.

    SectionQuestion to checkMeaning in this lesson
    InputWhat value does the program receive first?Values the user enters or values written in advance in the a taste of data analysis example.
    ProcessingWhat calculation or decision happens?The part Python runs in order to achieve the goal: read CSV data as a table, summarize it, and save it as a graph.
    OutputWhat result does the user check?This may be a print result, saved file, created graph, or changed data.

    Simply filling in this table yourself improves code comprehension. Beginners struggle partly because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error appears, do not delete code at random. If you check in the order below, you can find most beginner errors yourself.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check parentheses, quotation marks, colons, and commas.
    • Check whether the variable name exactly matches the name defined above.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look like clues instead of something scary. Python skill grows more from reading and fixing errors than from avoiding them completely.

    Application Ideas: Grow Today’s Lesson a Little

    Once this example feels familiar, keep the a taste of data analysis example and change one thing: an input value, an output sentence, a saving method, or a repeat count. You do not need to make a completely new example. At the beginner stage, many small variations are the best practice.

    • Change variable names in the example to make them more meaningful.
    • Refine output sentences so they read like guidance shown to a real user.
    • Deliberately check what happens when invalid input is entered.
    • Explain the code with comments to check your own understanding.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why a taste of data analysis is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    • Python Beginner 20-Lesson Complete Guide
    • Previous lesson: Python Beginner Lesson 17: Introduction to Folder and File Automation
    • Next lesson: Python Beginner Lesson 19: Fetch Web Data and APIs with requests
    • Business automation article collection

    FAQ

    Can I follow Python data analysis even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    The next lesson is Python Beginner Lesson 19: Fetch Web Data and APIs with requests. Based on the flow you practiced here, you will explore web data and APIs in more detail.

    References

    • Python Official Tutorial
    • Python Official Tutorial: Control Flow Tools
    • Python Official Tutorial: Data Structures
    • Python Official Tutorial: Modules
    • Python Official Tutorial: Input and Output

    Original Korean article: https://www.thinknote.co.kr/python-beginner-18-pandas-matplotlib/

  • Python Beginner Lesson 19: Fetch Web Data and APIs with requests

    In Python Beginner Lesson 19, we cover web data and APIs in detail at a beginner-friendly level. The final goal of this lesson is to send requests to a web API with requests and read JSON responses. Instead of stopping at copying code, we also check why this syntax is used and where beginners often make mistakes.

    Web services and automation tools exchange data through APIs. If you build a feel for HTTP and JSON at the beginner stage, later data collection, chatbots, and business-system integrations become easier to learn. Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: web data and APIs
    • Today’s goal: send requests to a web API with requests and read JSON responses
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 19: Fetch Web Data and APIs with requests - requests is a tool that sends requests to web servers or APIs and brings response data into your program.
    requests is a tool that sends requests to web servers or APIs and brings response data into your program.

    When learning web data and APIs, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • HTTP is the rule set for exchanging requests and responses on the web.
    • An API is an agreement that lets one program use another program’s features or data.
    • JSON is easy to understand as a structure that mixes dictionaries and lists.
    • Requests can fail, so status codes and exception handling are needed.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    HTTP status codeA number such as 200, 404, or 500 that represents the request result
    JSONA data format often used by web APIs
    timeoutA time limit that prevents waiting too long for a response

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 19: Fetch Web Data and APIs with requests - When you practice checking the status code and reading the JSON response, you build the basics for working with external data.
    When you practice checking the status code and reading the JSON response, you build the basics for working with external data.

    When you practice checking the status code and reading the JSON response, you build the basics for working with external data.

    import requests
    
    url = "https://api.github.com"
    response = requests.get(url, timeout=10)
    print("Status code:", response.status_code)
    
    if response.status_code == 200:
        data = response.json()
        print("Current user URL:", data.get("current_user_url"))
    else:
        print("The request failed.")

    Understand the Code Line by Line

    • requests.get() sends a request to the specified URL.
    • timeout=10 makes the program stop if there is no response for more than 10 seconds.
    • If status_code is 200, treat it as a successful response.
    • response.json() lets you read the JSON response like a Python dictionary.

    The important point at this stage is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditions, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code runs, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After changing something, always save and run the file again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether the explanation becomes friendlier for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    requests is not installedThis is a common beginner-stage problem.Install it with pip install requests.
    TimeoutThis is a common beginner-stage problem.It can happen when the network is slow or the server does not respond.
    JSONDecodeErrorThis is a common beginner-stage problem.It can happen when the response is not in JSON format.

    When an error occurs, first look at the last line of the error message. Then check the file name and line number. Most beginner errors happen around parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Check the status code of another public API.
    • Print the list of keys in the response JSON.
    • Print a more detailed guide message when the request fails.

    When solving practice problems, do not look for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    Web data and apis does not end with a small example. It appears again and again when organizing files in business automation, reading table data in data analysis, and handling response values in web APIs. The beginner syntax you learn now also becomes the basic language you use later with tools such as pandas, requests, and FastAPI.

    A Beginner-Friendly Analogy

    When you first see web data and APIs, syntax symbols may catch your eye first. But if you look at syntax only as symbols, you will quickly get tired. A better method is to understand it by role. The core of this lesson is to send requests to a web API with requests and read JSON responses. In other words, you are practicing how to decide what job to give Python and write the order of that job as code.

    Think of a cooking recipe. You prepare ingredients, handle them in order, control the heat, and finally serve the dish. Python code is similar. You prepare the needed values, process them in a defined order, and print or save the result. For beginners, building this sense of order is the most important part.

    Follow the Execution Flow Visually

    Before running code, think in the following three boxes. This habit helps not only with simple examples but also later when you build longer projects.

    SectionQuestion to checkMeaning in this lesson
    InputWhat value does the program receive first?Values the user enters or values written in advance in the web data and APIs example.
    ProcessingWhat calculation or decision happens?The part Python runs in order to achieve the goal: send requests to a web API with requests and read JSON responses.
    OutputWhat result does the user check?This may be a print result, saved file, created graph, or changed data.

    Simply filling in this table yourself improves code comprehension. Beginners struggle partly because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error appears, do not delete code at random. If you check in the order below, you can find most beginner errors yourself.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check parentheses, quotation marks, colons, and commas.
    • Check whether the variable name exactly matches the name defined above.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look like clues instead of something scary. Python skill grows more from reading and fixing errors than from avoiding them completely.

    Application Ideas: Grow Today’s Lesson a Little

    Once this example feels familiar, keep the web data and APIs example and change one thing: an input value, an output sentence, a saving method, or a repeat count. You do not need to make a completely new example. At the beginner stage, many small variations are the best practice.

    • Change variable names in the example to make them more meaningful.
    • Refine output sentences so they read like guidance shown to a real user.
    • Deliberately check what happens when invalid input is entered.
    • Explain the code with comments to check your own understanding.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why web data and APIs is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    • Python Beginner 20-Lesson Complete Guide
    • Previous lesson: Python Beginner Lesson 18: A Taste of Data Analysis with pandas and matplotlib
    • Next lesson: Python Beginner Lesson 20: Complete a Mini App with a Final Project
    • Business automation article collection

    FAQ

    Can I follow Python API even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    The next lesson is Python Beginner Lesson 20: Complete a Mini App with a Final Project. Based on the flow you practiced here, you will explore the final mini project in more detail.

    References

    • Python Official Tutorial
    • Python Official Tutorial: Control Flow Tools
    • Python Official Tutorial: Data Structures
    • Python Official Tutorial: Modules
    • Python Official Tutorial: Input and Output

    Original Korean article: https://www.thinknote.co.kr/python-beginner-19-web-api-requests/

  • Python Beginner Lesson 20: Complete a Mini App with a Final Project

    In Python Beginner Lesson 20, we cover final mini project in detail at a beginner-friendly level. The final goal is to combine beginner syntax into one complete flow. That flow covers data input, processing, storage, and visualization. Instead of stopping at copied code, we check why each part is used. We also note where beginners often make mistakes.

    The goal of the final lesson is not to add many new grammar rules. It is to connect the basics you have learned so far into one small result and build the feeling that “I can make something with Python too.” Today’s example is small, but it becomes a basic skeleton for later automation, data analysis, and web API learning.

    What You Will Learn in This Lesson

    • Core topic: final mini project
    • Today’s goal: combine beginner syntax into a complete flow for data input, processing, storage, and visualization
    • Practice flow: understand the concept → run the example → review the code → try an applied task
    • Recommended study time: 30–50 minutes

    Understand the Big Picture First

    Python Beginner Lesson 20: Complete a Mini App with a Final Project - A final project connects loading data, summarizing it, saving a chart, and checking the result into one app flow.
    A final project connects loading data, summarizing it, saving a chart, and checking the result into one app flow.

    When learning final mini project, the most important thing is not memorizing grammar names. You need to understand what role this concept plays inside a real program. At the beginner stage, keep asking the following three questions.

    • Where did this value come from?
    • In what order does this code run?
    • Where should I save the result if I want to use it again?

    Look Closely at the Core Concepts

    • Projects are easier to finish when you split features into small pieces.
    • The structure becomes clearer when you separate input, processing, storage, and output steps.
    • A README should describe how to run the project, required packages, and the file structure.
    • After finishing, leave improvement tasks so the project connects to your next stage of learning.

    At first, explanations alone may feel abstract. That is why it is helpful to run the example below right away and check the concept with your own eyes.

    Beginner Terms You Should Know

    TermSimple explanation
    Project structureAn organized shape for files, functions, and data flow
    READMEA document that explains the project and how to run it
    RefactoringImproving code readability while keeping the same behavior

    Practice Setup

    Create a new Python file and run the example below. Using lowercase English letters and numbers in the file name helps reduce errors. For example, save it as lesson.py or practice_01.py. After entering the code, do not change many things at once. Change it little by little while checking the result each time.

    Example Code

    Python Beginner Lesson 20: Complete a Mini App with a Final Project - The moment you check the finished mini app is when the syntax and tools learned earlier become a real result.
    The moment you check the finished mini app is when the syntax and tools learned earlier become a real result.

    The moment you check the finished mini app is when the syntax and tools learned earlier become a real result.

    import pandas as pd
    import matplotlib.pyplot as plt
    
    
    def load_data():
        return pd.DataFrame({
            "category": ["Food", "Transport", "Study", "Food"],
            "amount": [120000, 45000, 80000, 30000]
        })
    
    
    def summarize(data):
        return data.groupby("category")["amount"].sum()
    
    
    def save_chart(summary):
        summary.plot(kind="bar")
        plt.title("Spending by Category")
        plt.tight_layout()
        plt.savefig("expense-summary.png")
    
    
    data = load_data()
    summary = summarize(data)
    print(summary)
    save_chart(summary)

    Understand the Code Line by Line

    • load_data() prepares sample data. In a real project, you could replace it with CSV reading.
    • summarize() adds up amounts by category.
    • save_chart() saves the summarized result as a graph.
    • The last four lines run the whole flow in order.

    The important point at this stage is the “reading order” of the code. Python runs from top to bottom. Even when there are exceptional flows such as functions or conditions, beginners should first get used to the basic top-to-bottom flow.

    Change Values and Check the Result

    If the example code runs, now change only a very small part. Start with small changes such as one number, one string, or one variable name so errors are easier to find. After changing something, always save and run the file again.

    Part to changeWhat to check
    Input value or variable valueCheck how the result sentence changes.
    Output sentenceCheck whether the explanation becomes friendlier for the user.
    Code orderCheck whether changing the order causes an error or changes the result.

    Common Errors and How to Fix Them

    Error or situationWhy it happensHow to fix it
    Starting too bigThis is a common beginner-stage problem.Complete one small function first, then attach the next feature.
    Missing package installationThis is a common beginner-stage problem.It is helpful to write required packages in requirements.txt.
    Hard to rerunThis is a common beginner-stage problem.Leave the input file location and run command in the README.

    When an error occurs, first look at the last line of the error message. Then check the file name and line number. Most beginner errors happen around parentheses, quotation marks, indentation, variable names, and type conversion.

    Practice Problems to Try on Your Own

    • Change load_data() to a read_csv() approach.
    • Print the spending category with the largest total.
    • Write installation and run instructions in a README.md file.

    When solving practice problems, do not look for the answer code right away. First write the input, processing, and output flow on paper. Once the flow is visible, the code becomes much easier to write.

    Where Does This Connect in Real Work?

    Final mini project does not end with a small example. It appears again and again when organizing files in business automation, reading table data in data analysis, and handling response values in web APIs. The beginner syntax you learn now also becomes the basic language you use later with tools such as pandas, requests, and FastAPI.

    A Beginner-Friendly Analogy

    When you first see final mini project, syntax symbols may catch your eye first. But if you look at syntax only as symbols, you will quickly get tired. A better method is to understand it by role. The core of this lesson is to combine beginner syntax into a complete flow for data input, processing, storage, and visualization. In other words, you are practicing how to decide what job to give Python and write the order of that job as code.

    Think of a cooking recipe. You prepare ingredients, handle them in order, control the heat, and finally serve the dish. Python code is similar. You prepare the needed values, process them in a defined order, and print or save the result. For beginners, building this sense of order is the most important part.

    Follow the Execution Flow Visually

    Before running code, think in the following three boxes. This habit helps not only with simple examples but also later when you build longer projects.

    SectionQuestion to checkMeaning in this lesson
    InputWhat value does the program receive first?Values the user enters or values written in advance in the final mini project example.
    ProcessingWhat calculation or decision happens?The part Python runs in order to achieve the goal: combine beginner syntax into a complete flow for data input, processing, storage, and visualization.
    OutputWhat result does the user check?This may be a print result, saved file, created graph, or changed data.

    Simply filling in this table yourself improves code comprehension. Beginners struggle partly because they do not know syntax, but more often because they cannot separate input, processing, and output flow.

    Debugging Routine: What to Check When an Error Happens

    When an error appears, do not delete code at random. If you check in the order below, you can find most beginner errors yourself.

    • Read the last line of the error message.
    • Check the file name and line number.
    • On that line, check parentheses, quotation marks, colons, and commas.
    • Check whether the variable name exactly matches the name defined above.
    • Check whether a value that should be calculated as a number is still a string.
    • Undo the part you just changed and run the code again.

    If you repeat this routine, errors begin to look like clues instead of something scary. Python skill grows more from reading and fixing errors than from avoiding them completely.

    Application Ideas: Grow Today’s Lesson a Little

    Once this example feels familiar, keep the final mini project example and change one thing: an input value, an output sentence, a saving method, or a repeat count. You do not need to make a completely new example. At the beginner stage, many small variations are the best practice.

    • Change variable names in the example to make them more meaningful.
    • Refine output sentences so they read like guidance shown to a real user.
    • Deliberately check what happens when invalid input is entered.
    • Explain the code with comments to check your own understanding.
    • Try making the same result in a slightly different way.

    Lesson Checkpoints

    • ☐ I can explain in words why final mini project is needed.
    • ☐ I ran the example code myself.
    • ☐ I can explain the role of at least three lines of code.
    • ☐ When an error occurred, I checked the last line and the line number.
    • ☐ I changed and ran at least one practice problem on my own.

    Related Articles

    • Python Beginner 20-Lesson Complete Guide
    • Previous lesson: Python Beginner Lesson 19: Fetch Web Data and APIs with requests
    • Business automation article collection

    FAQ

    Can I follow Python final project even if I am completely new to Python?

    Yes. This lesson is written for readers who are learning programming for the first time. Focus on understanding the execution result and flow rather than memorizing the code.

    I followed the example exactly, but I get an error. What should I check first?

    Check parentheses, quotation marks, colons, indentation, and variable names first. Many beginner errors happen because quotation marks were entered strangely or a variable name differs by one character.

    The example code looks too short. Should I study longer code?

    At the beginner level, short code is better. The most stable way to improve is to understand short code accurately, then change values and add features one by one.

    What should I do next?

    Change and run at least one practice problem from this lesson. Then move to the next lesson, where the concepts you learned earlier will appear again naturally.

    Next Lesson Preview

    After completing Beginner Lesson 20, you can expand into intermediate topics such as virtual environments, package structure, testing, data analysis, web APIs, and automation projects.

    References

    • Python Official Tutorial
    • Python Official Tutorial: Control Flow Tools
    • Python Official Tutorial: Data Structures
    • Python Official Tutorial: Modules
    • Python Official Tutorial: Input and Output

    Original Korean article: https://www.thinknote.co.kr/python-beginner-20-final-project/

  • 파이썬 초급 20강: 최종 프로젝트로 미니 앱 완성하기

    파이썬 초급 20강: 최종 프로젝트로 미니 앱 완성하기

    파이썬 초급 20강에서는 최종 미니 프로젝트을 초보자 눈높이에서 자세히 다룹니다. 이번 강의의 최종 목표는 초급 문법을 묶어 데이터 입력, 처리, 저장, 시각화 흐름을 완성하는 것입니다. 단순히 코드를 복사하는 데서 끝내지 않고, 왜 이런 문법을 쓰는지와 어디에서 자주 실수하는지까지 함께 확인합니다.

    마지막 강의의 목표는 새로운 문법을 많이 넣는 것이 아닙니다. 지금까지 배운 기본기를 하나의 작은 결과물로 연결해 “나도 파이썬으로 뭔가 만들 수 있다”는 감각을 만드는 것입니다. 오늘 예제는 작지만, 이후 자동화·데이터 분석·웹 API 학습으로 이어지는 기본 뼈대가 됩니다.

    이번 강의에서 배울 내용

    • 핵심 주제: 최종 미니 프로젝트
    • 오늘의 목표: 초급 문법을 묶어 데이터 입력, 처리, 저장, 시각화 흐름을 완성하는 것
    • 실습 방식: 개념 이해 → 예제 실행 → 코드 해설 → 응용 과제
    • 권장 학습 시간: 30~50분

    먼저 큰 그림부터 이해하기

    파이썬 초급 20강: 최종 프로젝트로 미니 앱 완성하기 - 최종 프로젝트는 데이터 불러오기, 집계, 그래프 저장, 결과 확인을 하나의 앱 흐름으로 연결합니다.
    최종 프로젝트는 데이터 불러오기, 집계, 그래프 저장, 결과 확인을 하나의 앱 흐름으로 연결합니다.

    최종 미니 프로젝트을 배울 때 가장 중요한 것은 문법 이름을 외우는 것이 아닙니다. 실제 프로그램 안에서 이 개념이 어떤 역할을 하는지 이해해야 합니다. 초급 단계에서는 아래 세 가지 질문을 계속 떠올리면 좋습니다.

    • 이 값은 어디에서 왔는가?
    • 이 코드는 어떤 순서로 실행되는가?
    • 결과를 다시 사용하려면 어디에 저장해야 하는가?

    핵심 개념 자세히 보기

    • 프로젝트는 기능을 작게 나눠야 완성하기 쉽습니다.
    • 입력, 처리, 저장, 출력 단계를 구분하면 구조가 선명해집니다.
    • README에는 실행 방법, 필요한 패키지, 파일 구조를 적어야 합니다.
    • 완성 후에는 개선 과제를 남겨 다음 학습으로 연결합니다.

    처음에는 설명만 읽으면 추상적으로 느껴질 수 있습니다. 그래서 바로 아래 예제를 실행하면서 개념을 눈으로 확인하는 것이 좋습니다.

    초보자가 알아야 할 용어 정리

    용어 쉬운 설명
    프로젝트 구조 파일과 함수, 데이터 흐름을 정리한 형태
    README 프로젝트 설명과 실행 방법을 적는 문서
    리팩터링 동작은 유지하면서 코드를 더 읽기 좋게 정리하는 작업

    실습 준비

    아래 예제는 새 파이썬 파일을 만들어 실행하면 됩니다. 파일명은 영어 소문자와 숫자를 사용하면 오류를 줄일 수 있습니다. 예를 들어 lesson.py, practice_01.py처럼 저장해 보세요. 코드를 입력한 뒤에는 한 번에 많이 고치지 말고, 실행 결과를 확인하면서 조금씩 바꾸는 것이 좋습니다.

    예제 코드

    파이썬 초급 20강: 최종 프로젝트로 미니 앱 완성하기 - 완성된 미니 앱을 확인하는 과정은 앞에서 배운 문법과 도구가 실제 결과물로 이어지는 순간입니다.
    완성된 미니 앱을 확인하는 과정은 앞에서 배운 문법과 도구가 실제 결과물로 이어지는 순간입니다.
    import pandas as pd
    import matplotlib.pyplot as plt
    
    
    def load_data():
        return pd.DataFrame({
            "category": ["식비", "교통", "공부", "식비"],
            "amount": [120000, 45000, 80000, 30000]
        })
    
    
    def summarize(data):
        return data.groupby("category")["amount"].sum()
    
    
    def save_chart(summary):
        summary.plot(kind="bar")
        plt.title("카테고리별 지출")
        plt.tight_layout()
        plt.savefig("expense-summary.png")
    
    
    data = load_data()
    summary = summarize(data)
    print(summary)
    save_chart(summary)

    코드 한 줄씩 이해하기

    1. load_data()는 예제 데이터를 준비합니다. 실제 프로젝트에서는 CSV 읽기로 바꿀 수 있습니다.
    1. summarize()는 카테고리별 금액을 합산합니다.
    1. save_chart()는 요약 결과를 그래프로 저장합니다.
    1. 마지막 네 줄은 전체 흐름을 순서대로 실행합니다.

    이 단계에서 중요한 것은 코드를 ‘읽는 순서’입니다. 파이썬은 위에서 아래로 실행됩니다. 함수나 조건문처럼 예외적인 흐름이 있더라도, 초급자는 먼저 위에서 아래로 실행되는 기본 흐름을 몸에 익히면 됩니다.

    값을 바꿔 보며 확인하기

    예제 코드가 실행됐다면 이제 아주 작은 부분만 바꿔 보세요. 숫자 하나, 문자열 하나, 변수 이름 하나처럼 작은 변경부터 시작해야 오류를 찾기 쉽습니다. 변경 후에는 반드시 저장하고 다시 실행합니다.

    바꿔 볼 부분 확인할 것
    입력값 또는 변수값 결과 문장이 어떻게 달라지는지 확인합니다.
    출력 문장 사용자에게 더 친절한 설명이 되는지 확인합니다.
    코드 순서 순서를 바꾸면 오류가 나거나 결과가 달라지는지 확인합니다.

    자주 나는 오류와 해결 방법

    오류 또는 상황 왜 생기는가 해결 방법
    처음부터 크게 만들기 초급 단계에서 자주 만나는 문제입니다. 작은 함수 하나를 먼저 완성하고 다음 기능을 붙입니다.
    패키지 설치 누락 초급 단계에서 자주 만나는 문제입니다. 필요한 패키지를 requirements.txt에 적어 두면 좋습니다.
    재실행 어려움 초급 단계에서 자주 만나는 문제입니다. 입력 파일 위치와 실행 명령을 README에 남깁니다.

    오류가 나면 먼저 오류 메시지의 마지막 줄을 보세요. 그다음 파일명과 줄 번호를 확인합니다. 대부분의 초급 오류는 괄호, 따옴표, 들여쓰기, 변수 이름, 자료형 변환에서 발생합니다.

    혼자 해보는 연습 문제

    • load_data()를 read_csv() 방식으로 바꿔 보세요.
    • 가장 큰 지출 카테고리를 출력해 보세요.
    • README.md 파일에 설치와 실행 방법을 적어 보세요.

    연습 문제를 풀 때는 정답 코드를 바로 찾기보다, 먼저 종이에 입력·처리·출력 흐름을 적어 보세요. 흐름이 보이면 코드는 훨씬 쉽게 작성됩니다.

    실무에서는 어디에 연결될까?

    최종 미니 프로젝트은 작은 예제에서 끝나지 않습니다. 업무 자동화에서는 파일을 정리하고, 데이터 분석에서는 표 데이터를 읽고, 웹 API에서는 응답 값을 다룰 때 계속 등장합니다. 지금 배우는 초급 문법은 이후 pandas, requests, FastAPI 같은 도구를 사용할 때도 기본 언어가 됩니다.

    초보자를 위한 이해 비유

    최종 미니 프로젝트을 처음 볼 때는 문법 기호가 먼저 눈에 들어옵니다. 하지만 문법을 기호로만 보면 금방 지칩니다. 더 좋은 방법은 역할로 이해하는 것입니다. 이번 강의의 핵심은 초급 문법을 묶어 데이터 입력, 처리, 저장, 시각화 흐름을 완성하는 것입니다. 즉, 파이썬에게 어떤 일을 맡길지 정하고, 그 일을 처리하는 순서를 코드로 적는 연습입니다.

    예를 들어 요리 레시피를 생각해 보세요. 재료를 준비하고, 순서대로 손질하고, 불 조절을 하고, 마지막에 그릇에 담습니다. 파이썬 코드도 비슷합니다. 필요한 값을 준비하고, 정해진 순서로 처리하고, 결과를 출력하거나 저장합니다. 초급자는 이 순서 감각을 잡는 것이 가장 중요합니다.

    실행 흐름을 눈으로 따라가기

    코드를 실행하기 전에는 아래처럼 세 칸으로 나누어 생각해 보세요. 이 습관은 간단한 예제뿐 아니라 나중에 긴 프로젝트를 만들 때도 도움이 됩니다.

    구분 확인 질문 이번 강의에서의 의미
    입력 프로그램이 처음 받는 값은 무엇인가? 최종 미니 프로젝트 예제에서 사용자가 넣거나 코드에 미리 적어 둔 값입니다.
    처리 어떤 계산이나 판단을 하는가? 초급 문법을 묶어 데이터 입력, 처리, 저장, 시각화 흐름을 완성하는 것을 달성하기 위해 파이썬이 순서대로 실행하는 부분입니다.
    출력 사용자가 확인하는 결과는 무엇인가? print 결과, 저장된 파일, 만들어진 그래프, 바뀐 데이터 등이 됩니다.

    이 표를 직접 채워 보는 것만으로도 코드 이해력이 좋아집니다. 초급자가 어려움을 느끼는 이유는 문법을 몰라서이기도 하지만, 더 자주 발생하는 이유는 입력·처리·출력 흐름을 구분하지 못하기 때문입니다.

    디버깅 루틴: 오류가 났을 때 순서대로 보기

    오류가 나면 무작정 코드를 지우지 마세요. 아래 순서대로 확인하면 대부분의 초급 오류를 스스로 찾을 수 있습니다.

    1. 오류 메시지의 마지막 줄을 읽습니다.
    1. 파일명과 줄 번호를 확인합니다.
    1. 그 줄에서 괄호, 따옴표, 콜론, 쉼표가 맞는지 봅니다.
    1. 변수 이름을 위에서 정의한 이름과 똑같이 썼는지 확인합니다.
    1. 숫자로 계산해야 하는 값이 문자열로 남아 있지 않은지 확인합니다.
    1. 방금 수정한 부분을 되돌려 보고 다시 실행합니다.

    이 루틴을 반복하면 오류가 무서운 것이 아니라 단서처럼 보이기 시작합니다. 파이썬 실력은 오류를 피하는 능력보다 오류를 읽고 고치는 능력에서 더 많이 자랍니다.

    응용 방향: 오늘 배운 내용을 조금 더 키우기

    이번 예제가 익숙해졌다면 최종 미니 프로젝트을 그대로 두고 입력값, 출력 문장, 저장 방식, 반복 횟수 중 하나를 바꿔 보세요. 예제를 완전히 새로 만들 필요는 없습니다. 초급 단계에서는 작은 변형을 많이 해보는 것이 가장 좋습니다.

    • 예제의 변수 이름을 더 의미 있게 바꿔 봅니다.
    • 출력 문장을 실제 사용자에게 보여 주는 안내문처럼 다듬어 봅니다.
    • 잘못된 입력이 들어왔을 때 어떤 일이 생기는지 일부러 확인해 봅니다.
    • 코드를 주석으로 설명해 보며 스스로 이해한 내용을 점검합니다.
    • 같은 결과를 조금 다른 방식으로 만들 수 있는지 시도해 봅니다.

    이번 강의 체크포인트

    • ☐ 최종 미니 프로젝트이 왜 필요한지 말로 설명할 수 있다.
    • ☐ 예제 코드를 직접 실행했다.
    • ☐ 코드 한 줄의 역할을 최소 3개 이상 설명할 수 있다.
    • ☐ 오류가 났을 때 마지막 줄과 줄 번호를 확인했다.
    • ☐ 연습 문제 중 하나를 스스로 바꿔 실행했다.

    함께 보면 좋은 글

    FAQ

    파이썬 최종 프로젝트은 완전히 처음 배워도 따라갈 수 있나요?

    네. 이번 강의는 프로그래밍을 처음 배우는 독자를 기준으로 구성했습니다. 코드를 외우는 것보다 실행 결과와 흐름을 이해하는 데 집중하면 됩니다.

    예제를 그대로 따라 했는데 오류가 납니다. 무엇부터 확인해야 하나요?

    괄호, 따옴표, 콜론, 들여쓰기, 변수 이름을 먼저 확인하세요. 특히 한글 입력 상태에서 따옴표가 이상하게 들어가거나, 변수 이름을 한 글자 다르게 쓰는 경우가 많습니다.

    예제 코드가 너무 짧아 보입니다. 더 길게 공부해야 하나요?

    초급에서는 짧은 코드가 더 좋습니다. 짧은 코드를 정확히 이해한 뒤 값을 바꾸고 기능을 하나씩 추가하는 방식이 실력이 가장 안정적으로 늘어납니다.

    다음 단계로 무엇을 하면 좋을까요?

    이번 강의의 연습 문제를 하나 이상 바꿔 실행해 보세요. 그다음 다음 강의로 넘어가면 앞에서 배운 개념이 자연스럽게 다시 등장합니다.

    다음 강의 예고

    초급 20강을 마쳤다면 이제 중급 과정에서 가상환경, 패키지 구조, 테스트, 데이터 분석, 웹 API, 자동화 프로젝트로 확장할 수 있습니다.

    참고자료

  • 파이썬 초급 19강: requests로 웹 데이터와 API 가져오기

    파이썬 초급 19강: requests로 웹 데이터와 API 가져오기

    파이썬 초급 19강에서는 웹 데이터와 API을 초보자 눈높이에서 자세히 다룹니다. 이번 강의의 최종 목표는 requests로 웹 API에 요청을 보내고 JSON 응답을 읽는 것입니다. 단순히 코드를 복사하는 데서 끝내지 않고, 왜 이런 문법을 쓰는지와 어디에서 자주 실수하는지까지 함께 확인합니다.

    웹 서비스와 자동화 도구는 API로 데이터를 주고받습니다. 초급 단계에서 HTTP와 JSON 감각을 잡아 두면 이후 데이터 수집, 챗봇, 업무 시스템 연동을 배우기 쉬워집니다. 오늘 예제는 작지만, 이후 자동화·데이터 분석·웹 API 학습으로 이어지는 기본 뼈대가 됩니다.

    이번 강의에서 배울 내용

    • 핵심 주제: 웹 데이터와 API
    • 오늘의 목표: requests로 웹 API에 요청을 보내고 JSON 응답을 읽는 것
    • 실습 방식: 개념 이해 → 예제 실행 → 코드 해설 → 응용 과제
    • 권장 학습 시간: 30~50분

    먼저 큰 그림부터 이해하기

    파이썬 초급 19강: requests로 웹 데이터와 API 가져오기 - requests는 웹 서버나 API에 요청을 보내고 응답 데이터를 프로그램 안으로 가져오는 도구입니다.
    requests는 웹 서버나 API에 요청을 보내고 응답 데이터를 프로그램 안으로 가져오는 도구입니다.

    웹 데이터와 API을 배울 때 가장 중요한 것은 문법 이름을 외우는 것이 아닙니다. 실제 프로그램 안에서 이 개념이 어떤 역할을 하는지 이해해야 합니다. 초급 단계에서는 아래 세 가지 질문을 계속 떠올리면 좋습니다.

    • 이 값은 어디에서 왔는가?
    • 이 코드는 어떤 순서로 실행되는가?
    • 결과를 다시 사용하려면 어디에 저장해야 하는가?

    핵심 개념 자세히 보기

    • HTTP는 웹에서 요청과 응답을 주고받는 규칙입니다.
    • API는 프로그램이 다른 프로그램의 기능이나 데이터를 사용할 수 있게 만든 약속입니다.
    • JSON은 딕셔너리와 리스트가 섞인 구조로 이해하면 쉽습니다.
    • 요청은 실패할 수 있으므로 상태 코드와 예외 처리가 필요합니다.

    처음에는 설명만 읽으면 추상적으로 느껴질 수 있습니다. 그래서 바로 아래 예제를 실행하면서 개념을 눈으로 확인하는 것이 좋습니다.

    초보자가 알아야 할 용어 정리

    용어 쉬운 설명
    HTTP 상태 코드 200, 404, 500처럼 요청 결과를 나타내는 숫자
    JSON 웹 API에서 자주 쓰는 데이터 형식
    timeout 응답을 너무 오래 기다리지 않도록 정하는 제한 시간

    실습 준비

    아래 예제는 새 파이썬 파일을 만들어 실행하면 됩니다. 파일명은 영어 소문자와 숫자를 사용하면 오류를 줄일 수 있습니다. 예를 들어 lesson.py, practice_01.py처럼 저장해 보세요. 코드를 입력한 뒤에는 한 번에 많이 고치지 말고, 실행 결과를 확인하면서 조금씩 바꾸는 것이 좋습니다.

    예제 코드

    파이썬 초급 19강: requests로 웹 데이터와 API 가져오기 - 상태 코드를 확인하고 JSON 응답을 읽는 흐름을 익히면 외부 데이터를 다루는 기본기가 생깁니다.
    상태 코드를 확인하고 JSON 응답을 읽는 흐름을 익히면 외부 데이터를 다루는 기본기가 생깁니다.
    import requests
    
    url = "https://api.github.com"
    response = requests.get(url, timeout=10)
    print("상태 코드:", response.status_code)
    
    if response.status_code == 200:
        data = response.json()
        print("현재 사용자 URL:", data.get("current_user_url"))
    else:
        print("요청에 실패했습니다.")

    코드 한 줄씩 이해하기

    1. requests.get()으로 지정한 URL에 요청을 보냅니다.
    1. timeout=10은 10초 넘게 응답이 없으면 멈추게 합니다.
    1. status_code가 200이면 정상 응답으로 봅니다.
    1. response.json()은 JSON 응답을 파이썬 딕셔너리처럼 읽게 해 줍니다.

    이 단계에서 중요한 것은 코드를 ‘읽는 순서’입니다. 파이썬은 위에서 아래로 실행됩니다. 함수나 조건문처럼 예외적인 흐름이 있더라도, 초급자는 먼저 위에서 아래로 실행되는 기본 흐름을 몸에 익히면 됩니다.

    값을 바꿔 보며 확인하기

    예제 코드가 실행됐다면 이제 아주 작은 부분만 바꿔 보세요. 숫자 하나, 문자열 하나, 변수 이름 하나처럼 작은 변경부터 시작해야 오류를 찾기 쉽습니다. 변경 후에는 반드시 저장하고 다시 실행합니다.

    바꿔 볼 부분 확인할 것
    입력값 또는 변수값 결과 문장이 어떻게 달라지는지 확인합니다.
    출력 문장 사용자에게 더 친절한 설명이 되는지 확인합니다.
    코드 순서 순서를 바꾸면 오류가 나거나 결과가 달라지는지 확인합니다.

    자주 나는 오류와 해결 방법

    오류 또는 상황 왜 생기는가 해결 방법
    requests 미설치 초급 단계에서 자주 만나는 문제입니다. pip install requests로 설치합니다.
    Timeout 초급 단계에서 자주 만나는 문제입니다. 네트워크가 느리거나 서버가 응답하지 않을 때 발생할 수 있습니다.
    JSONDecodeError 초급 단계에서 자주 만나는 문제입니다. 응답이 JSON 형식이 아닐 때 발생할 수 있습니다.

    오류가 나면 먼저 오류 메시지의 마지막 줄을 보세요. 그다음 파일명과 줄 번호를 확인합니다. 대부분의 초급 오류는 괄호, 따옴표, 들여쓰기, 변수 이름, 자료형 변환에서 발생합니다.

    혼자 해보는 연습 문제

    • 다른 공개 API의 상태 코드를 확인해 보세요.
    • 응답 JSON의 키 목록을 출력해 보세요.
    • 요청 실패 시 안내 문장을 더 자세히 출력해 보세요.

    연습 문제를 풀 때는 정답 코드를 바로 찾기보다, 먼저 종이에 입력·처리·출력 흐름을 적어 보세요. 흐름이 보이면 코드는 훨씬 쉽게 작성됩니다.

    실무에서는 어디에 연결될까?

    웹 데이터와 API은 작은 예제에서 끝나지 않습니다. 업무 자동화에서는 파일을 정리하고, 데이터 분석에서는 표 데이터를 읽고, 웹 API에서는 응답 값을 다룰 때 계속 등장합니다. 지금 배우는 초급 문법은 이후 pandas, requests, FastAPI 같은 도구를 사용할 때도 기본 언어가 됩니다.

    초보자를 위한 이해 비유

    웹 데이터와 API을 처음 볼 때는 문법 기호가 먼저 눈에 들어옵니다. 하지만 문법을 기호로만 보면 금방 지칩니다. 더 좋은 방법은 역할로 이해하는 것입니다. 이번 강의의 핵심은 requests로 웹 API에 요청을 보내고 JSON 응답을 읽는 것입니다. 즉, 파이썬에게 어떤 일을 맡길지 정하고, 그 일을 처리하는 순서를 코드로 적는 연습입니다.

    예를 들어 요리 레시피를 생각해 보세요. 재료를 준비하고, 순서대로 손질하고, 불 조절을 하고, 마지막에 그릇에 담습니다. 파이썬 코드도 비슷합니다. 필요한 값을 준비하고, 정해진 순서로 처리하고, 결과를 출력하거나 저장합니다. 초급자는 이 순서 감각을 잡는 것이 가장 중요합니다.

    실행 흐름을 눈으로 따라가기

    코드를 실행하기 전에는 아래처럼 세 칸으로 나누어 생각해 보세요. 이 습관은 간단한 예제뿐 아니라 나중에 긴 프로젝트를 만들 때도 도움이 됩니다.

    구분 확인 질문 이번 강의에서의 의미
    입력 프로그램이 처음 받는 값은 무엇인가? 웹 데이터와 API 예제에서 사용자가 넣거나 코드에 미리 적어 둔 값입니다.
    처리 어떤 계산이나 판단을 하는가? requests로 웹 API에 요청을 보내고 JSON 응답을 읽는 것을 달성하기 위해 파이썬이 순서대로 실행하는 부분입니다.
    출력 사용자가 확인하는 결과는 무엇인가? print 결과, 저장된 파일, 만들어진 그래프, 바뀐 데이터 등이 됩니다.

    이 표를 직접 채워 보는 것만으로도 코드 이해력이 좋아집니다. 초급자가 어려움을 느끼는 이유는 문법을 몰라서이기도 하지만, 더 자주 발생하는 이유는 입력·처리·출력 흐름을 구분하지 못하기 때문입니다.

    디버깅 루틴: 오류가 났을 때 순서대로 보기

    오류가 나면 무작정 코드를 지우지 마세요. 아래 순서대로 확인하면 대부분의 초급 오류를 스스로 찾을 수 있습니다.

    1. 오류 메시지의 마지막 줄을 읽습니다.
    1. 파일명과 줄 번호를 확인합니다.
    1. 그 줄에서 괄호, 따옴표, 콜론, 쉼표가 맞는지 봅니다.
    1. 변수 이름을 위에서 정의한 이름과 똑같이 썼는지 확인합니다.
    1. 숫자로 계산해야 하는 값이 문자열로 남아 있지 않은지 확인합니다.
    1. 방금 수정한 부분을 되돌려 보고 다시 실행합니다.

    이 루틴을 반복하면 오류가 무서운 것이 아니라 단서처럼 보이기 시작합니다. 파이썬 실력은 오류를 피하는 능력보다 오류를 읽고 고치는 능력에서 더 많이 자랍니다.

    응용 방향: 오늘 배운 내용을 조금 더 키우기

    이번 예제가 익숙해졌다면 웹 데이터와 API을 그대로 두고 입력값, 출력 문장, 저장 방식, 반복 횟수 중 하나를 바꿔 보세요. 예제를 완전히 새로 만들 필요는 없습니다. 초급 단계에서는 작은 변형을 많이 해보는 것이 가장 좋습니다.

    • 예제의 변수 이름을 더 의미 있게 바꿔 봅니다.
    • 출력 문장을 실제 사용자에게 보여 주는 안내문처럼 다듬어 봅니다.
    • 잘못된 입력이 들어왔을 때 어떤 일이 생기는지 일부러 확인해 봅니다.
    • 코드를 주석으로 설명해 보며 스스로 이해한 내용을 점검합니다.
    • 같은 결과를 조금 다른 방식으로 만들 수 있는지 시도해 봅니다.

    이번 강의 체크포인트

    • ☐ 웹 데이터와 API이 왜 필요한지 말로 설명할 수 있다.
    • ☐ 예제 코드를 직접 실행했다.
    • ☐ 코드 한 줄의 역할을 최소 3개 이상 설명할 수 있다.
    • ☐ 오류가 났을 때 마지막 줄과 줄 번호를 확인했다.
    • ☐ 연습 문제 중 하나를 스스로 바꿔 실행했다.

    함께 보면 좋은 글

    FAQ

    파이썬 API은 완전히 처음 배워도 따라갈 수 있나요?

    네. 이번 강의는 프로그래밍을 처음 배우는 독자를 기준으로 구성했습니다. 코드를 외우는 것보다 실행 결과와 흐름을 이해하는 데 집중하면 됩니다.

    예제를 그대로 따라 했는데 오류가 납니다. 무엇부터 확인해야 하나요?

    괄호, 따옴표, 콜론, 들여쓰기, 변수 이름을 먼저 확인하세요. 특히 한글 입력 상태에서 따옴표가 이상하게 들어가거나, 변수 이름을 한 글자 다르게 쓰는 경우가 많습니다.

    예제 코드가 너무 짧아 보입니다. 더 길게 공부해야 하나요?

    초급에서는 짧은 코드가 더 좋습니다. 짧은 코드를 정확히 이해한 뒤 값을 바꾸고 기능을 하나씩 추가하는 방식이 실력이 가장 안정적으로 늘어납니다.

    다음 단계로 무엇을 하면 좋을까요?

    이번 강의의 연습 문제를 하나 이상 바꿔 실행해 보세요. 그다음 다음 강의로 넘어가면 앞에서 배운 개념이 자연스럽게 다시 등장합니다.

    다음 강의 예고

    다음 강의는 파이썬 초급 20강: 최종 프로젝트로 미니 앱 완성하기입니다. 이번 강의에서 익힌 흐름을 바탕으로 최종 미니 프로젝트을 더 구체적으로 다루겠습니다.

    참고자료

  • 파이썬 초급 17강: 폴더와 파일 작업 자동화 입문

    파이썬 초급 17강: 폴더와 파일 작업 자동화 입문

    파이썬 초급 17강에서는 파일 자동화을 초보자 눈높이에서 자세히 다룹니다. 이번 강의의 최종 목표는 폴더 안 파일 정보를 모아 CSV 리포트로 만드는 것입니다. 단순히 코드를 복사하는 데서 끝내지 않고, 왜 이런 문법을 쓰는지와 어디에서 자주 실수하는지까지 함께 확인합니다.

    업무 자동화는 거창한 AI부터 시작하지 않습니다. 폴더 안 파일 목록을 정리하고, 확장자별로 분류하고, 보고서로 저장하는 것만으로도 시간을 줄일 수 있습니다. 오늘 예제는 작지만, 이후 자동화·데이터 분석·웹 API 학습으로 이어지는 기본 뼈대가 됩니다.

    이번 강의에서 배울 내용

    • 핵심 주제: 파일 자동화
    • 오늘의 목표: 폴더 안 파일 정보를 모아 CSV 리포트로 만드는 것
    • 실습 방식: 개념 이해 → 예제 실행 → 코드 해설 → 응용 과제
    • 권장 학습 시간: 30~50분

    먼저 큰 그림부터 이해하기

    파이썬 초급 17강: 폴더와 파일 작업 자동화 입문 - 파일 자동화는 흩어진 파일을 규칙에 따라 정리하고 반복적인 확인 작업을 줄이는 방식입니다.
    파일 자동화는 흩어진 파일을 규칙에 따라 정리하고 반복적인 확인 작업을 줄이는 방식입니다.

    파일 자동화을 배울 때 가장 중요한 것은 문법 이름을 외우는 것이 아닙니다. 실제 프로그램 안에서 이 개념이 어떤 역할을 하는지 이해해야 합니다. 초급 단계에서는 아래 세 가지 질문을 계속 떠올리면 좋습니다.

    • 이 값은 어디에서 왔는가?
    • 이 코드는 어떤 순서로 실행되는가?
    • 결과를 다시 사용하려면 어디에 저장해야 하는가?

    핵심 개념 자세히 보기

    • 폴더 순회는 특정 폴더 안 파일을 하나씩 확인하는 작업입니다.
    • 파일 크기, 확장자, 수정일 같은 정보는 자동 리포트에 자주 쓰입니다.
    • 처음 자동화할 때는 원본 파일을 바꾸지 말고 읽기와 보고서 생성부터 시작해야 안전합니다.

    처음에는 설명만 읽으면 추상적으로 느껴질 수 있습니다. 그래서 바로 아래 예제를 실행하면서 개념을 눈으로 확인하는 것이 좋습니다.

    초보자가 알아야 할 용어 정리

    용어 쉬운 설명
    iterdir 폴더 안 항목을 하나씩 꺼내는 pathlib 메서드
    stat 파일 크기와 수정 시간 같은 정보를 가져오는 기능
    리포트 자동화 반복 확인 결과를 표나 파일로 저장하는 작업

    실습 준비

    아래 예제는 새 파이썬 파일을 만들어 실행하면 됩니다. 파일명은 영어 소문자와 숫자를 사용하면 오류를 줄일 수 있습니다. 예를 들어 lesson.py, practice_01.py처럼 저장해 보세요. 코드를 입력한 뒤에는 한 번에 많이 고치지 말고, 실행 결과를 확인하면서 조금씩 바꾸는 것이 좋습니다.

    예제 코드

    파이썬 초급 17강: 폴더와 파일 작업 자동화 입문 - 폴더를 훑어 파일 정보를 모으고 보고서로 저장하면 자동화의 효과를 바로 체감할 수 있습니다.
    폴더를 훑어 파일 정보를 모으고 보고서로 저장하면 자동화의 효과를 바로 체감할 수 있습니다.
    from pathlib import Path
    import csv
    
    folder = Path(".")
    files = []
    for path in folder.iterdir():
        if path.is_file():
            files.append([path.name, path.suffix, path.stat().st_size])
    
    with open("file_report.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["파일명", "확장자", "크기"])
        writer.writerows(files)
    
    print(f"{len(files)}개 파일 정보를 저장했습니다.")

    코드 한 줄씩 이해하기

    1. 현재 폴더를 Path(“.”)로 지정합니다.
    1. iterdir()로 폴더 안 항목을 하나씩 확인합니다.
    1. is_file()로 파일만 골라냅니다.
    1. 파일명, 확장자, 크기를 리스트로 모아 CSV에 저장합니다.

    이 단계에서 중요한 것은 코드를 ‘읽는 순서’입니다. 파이썬은 위에서 아래로 실행됩니다. 함수나 조건문처럼 예외적인 흐름이 있더라도, 초급자는 먼저 위에서 아래로 실행되는 기본 흐름을 몸에 익히면 됩니다.

    값을 바꿔 보며 확인하기

    예제 코드가 실행됐다면 이제 아주 작은 부분만 바꿔 보세요. 숫자 하나, 문자열 하나, 변수 이름 하나처럼 작은 변경부터 시작해야 오류를 찾기 쉽습니다. 변경 후에는 반드시 저장하고 다시 실행합니다.

    바꿔 볼 부분 확인할 것
    입력값 또는 변수값 결과 문장이 어떻게 달라지는지 확인합니다.
    출력 문장 사용자에게 더 친절한 설명이 되는지 확인합니다.
    코드 순서 순서를 바꾸면 오류가 나거나 결과가 달라지는지 확인합니다.

    자주 나는 오류와 해결 방법

    오류 또는 상황 왜 생기는가 해결 방법
    PermissionError 초급 단계에서 자주 만나는 문제입니다. 권한이 없는 파일이나 폴더에 접근할 때 발생합니다.
    원본 변경 위험 초급 단계에서 자주 만나는 문제입니다. rename이나 unlink 같은 명령은 백업 후 사용합니다.
    상대 경로 혼동 초급 단계에서 자주 만나는 문제입니다. 현재 실행 위치가 어디인지 print(Path.cwd())로 확인합니다.

    오류가 나면 먼저 오류 메시지의 마지막 줄을 보세요. 그다음 파일명과 줄 번호를 확인합니다. 대부분의 초급 오류는 괄호, 따옴표, 들여쓰기, 변수 이름, 자료형 변환에서 발생합니다.

    혼자 해보는 연습 문제

    • 특정 확장자 .txt 파일만 리포트에 넣어 보세요.
    • 크기가 큰 파일 순서로 정렬해 보세요.
    • 하위 폴더까지 포함하려면 rglob()을 찾아 사용해 보세요.

    연습 문제를 풀 때는 정답 코드를 바로 찾기보다, 먼저 종이에 입력·처리·출력 흐름을 적어 보세요. 흐름이 보이면 코드는 훨씬 쉽게 작성됩니다.

    실무에서는 어디에 연결될까?

    파일 자동화은 작은 예제에서 끝나지 않습니다. 업무 자동화에서는 파일을 정리하고, 데이터 분석에서는 표 데이터를 읽고, 웹 API에서는 응답 값을 다룰 때 계속 등장합니다. 지금 배우는 초급 문법은 이후 pandas, requests, FastAPI 같은 도구를 사용할 때도 기본 언어가 됩니다.

    초보자를 위한 이해 비유

    파일 자동화을 처음 볼 때는 문법 기호가 먼저 눈에 들어옵니다. 하지만 문법을 기호로만 보면 금방 지칩니다. 더 좋은 방법은 역할로 이해하는 것입니다. 이번 강의의 핵심은 폴더 안 파일 정보를 모아 CSV 리포트로 만드는 것입니다. 즉, 파이썬에게 어떤 일을 맡길지 정하고, 그 일을 처리하는 순서를 코드로 적는 연습입니다.

    예를 들어 요리 레시피를 생각해 보세요. 재료를 준비하고, 순서대로 손질하고, 불 조절을 하고, 마지막에 그릇에 담습니다. 파이썬 코드도 비슷합니다. 필요한 값을 준비하고, 정해진 순서로 처리하고, 결과를 출력하거나 저장합니다. 초급자는 이 순서 감각을 잡는 것이 가장 중요합니다.

    실행 흐름을 눈으로 따라가기

    코드를 실행하기 전에는 아래처럼 세 칸으로 나누어 생각해 보세요. 이 습관은 간단한 예제뿐 아니라 나중에 긴 프로젝트를 만들 때도 도움이 됩니다.

    구분 확인 질문 이번 강의에서의 의미
    입력 프로그램이 처음 받는 값은 무엇인가? 파일 자동화 예제에서 사용자가 넣거나 코드에 미리 적어 둔 값입니다.
    처리 어떤 계산이나 판단을 하는가? 폴더 안 파일 정보를 모아 CSV 리포트로 만드는 것을 달성하기 위해 파이썬이 순서대로 실행하는 부분입니다.
    출력 사용자가 확인하는 결과는 무엇인가? print 결과, 저장된 파일, 만들어진 그래프, 바뀐 데이터 등이 됩니다.

    이 표를 직접 채워 보는 것만으로도 코드 이해력이 좋아집니다. 초급자가 어려움을 느끼는 이유는 문법을 몰라서이기도 하지만, 더 자주 발생하는 이유는 입력·처리·출력 흐름을 구분하지 못하기 때문입니다.

    디버깅 루틴: 오류가 났을 때 순서대로 보기

    오류가 나면 무작정 코드를 지우지 마세요. 아래 순서대로 확인하면 대부분의 초급 오류를 스스로 찾을 수 있습니다.

    1. 오류 메시지의 마지막 줄을 읽습니다.
    1. 파일명과 줄 번호를 확인합니다.
    1. 그 줄에서 괄호, 따옴표, 콜론, 쉼표가 맞는지 봅니다.
    1. 변수 이름을 위에서 정의한 이름과 똑같이 썼는지 확인합니다.
    1. 숫자로 계산해야 하는 값이 문자열로 남아 있지 않은지 확인합니다.
    1. 방금 수정한 부분을 되돌려 보고 다시 실행합니다.

    이 루틴을 반복하면 오류가 무서운 것이 아니라 단서처럼 보이기 시작합니다. 파이썬 실력은 오류를 피하는 능력보다 오류를 읽고 고치는 능력에서 더 많이 자랍니다.

    응용 방향: 오늘 배운 내용을 조금 더 키우기

    이번 예제가 익숙해졌다면 파일 자동화을 그대로 두고 입력값, 출력 문장, 저장 방식, 반복 횟수 중 하나를 바꿔 보세요. 예제를 완전히 새로 만들 필요는 없습니다. 초급 단계에서는 작은 변형을 많이 해보는 것이 가장 좋습니다.

    • 예제의 변수 이름을 더 의미 있게 바꿔 봅니다.
    • 출력 문장을 실제 사용자에게 보여 주는 안내문처럼 다듬어 봅니다.
    • 잘못된 입력이 들어왔을 때 어떤 일이 생기는지 일부러 확인해 봅니다.
    • 코드를 주석으로 설명해 보며 스스로 이해한 내용을 점검합니다.
    • 같은 결과를 조금 다른 방식으로 만들 수 있는지 시도해 봅니다.

    이번 강의 체크포인트

    • ☐ 파일 자동화이 왜 필요한지 말로 설명할 수 있다.
    • ☐ 예제 코드를 직접 실행했다.
    • ☐ 코드 한 줄의 역할을 최소 3개 이상 설명할 수 있다.
    • ☐ 오류가 났을 때 마지막 줄과 줄 번호를 확인했다.
    • ☐ 연습 문제 중 하나를 스스로 바꿔 실행했다.

    함께 보면 좋은 글

    FAQ

    파이썬 자동화은 완전히 처음 배워도 따라갈 수 있나요?

    네. 이번 강의는 프로그래밍을 처음 배우는 독자를 기준으로 구성했습니다. 코드를 외우는 것보다 실행 결과와 흐름을 이해하는 데 집중하면 됩니다.

    예제를 그대로 따라 했는데 오류가 납니다. 무엇부터 확인해야 하나요?

    괄호, 따옴표, 콜론, 들여쓰기, 변수 이름을 먼저 확인하세요. 특히 한글 입력 상태에서 따옴표가 이상하게 들어가거나, 변수 이름을 한 글자 다르게 쓰는 경우가 많습니다.

    예제 코드가 너무 짧아 보입니다. 더 길게 공부해야 하나요?

    초급에서는 짧은 코드가 더 좋습니다. 짧은 코드를 정확히 이해한 뒤 값을 바꾸고 기능을 하나씩 추가하는 방식이 실력이 가장 안정적으로 늘어납니다.

    다음 단계로 무엇을 하면 좋을까요?

    이번 강의의 연습 문제를 하나 이상 바꿔 실행해 보세요. 그다음 다음 강의로 넘어가면 앞에서 배운 개념이 자연스럽게 다시 등장합니다.

    다음 강의 예고

    다음 강의는 파이썬 초급 18강: pandas와 matplotlib 데이터 분석 맛보기입니다. 이번 강의에서 익힌 흐름을 바탕으로 데이터 분석 맛보기을 더 구체적으로 다루겠습니다.

    참고자료