05-3 Python’s Package

What is a Package?

In Python, a package is a tool for systematically managing modules. A module is a single Python file that can contain related functions and classes. Packages group these modules together in a directory structure to organize and manage them, greatly enhancing code readability and reusability in large projects.

Using packages allows the separation of namespaces so that the same module name can be used in different packages. This prevents code collisions, maximizes maintainability, and enhances the reusability of modules. Understanding and using packages is essential for Python programmers.

Creating and Components of a Package

How to Create a Package

To create a Python package, you need to follow a specific directory structure. Generally, the package directory must contain one or more Python modules and a special file named __init__.py. The __init__.py file initializes the package and makes Python recognize the directory as a package.

Here is a basic example of package creation:


my_package/
   ├── __init__.py
   ├── module1.py
   └── module2.py
        

Role of the __init__.py File

The __init__.py file is a collection of code that executes when the package is initialized. This file can be empty or include initialization code for modules, classes, or functions. This allows specific modules to be automatically imported or initialized when using the package.

Installing and Managing Packages

PyPI and pip

PyPI (The Python Package Index) is the official repository that hosts thousands of user-generated packages.  pip is a package management tool that allows you to access PyPI to install, upgrade, and remove packages. Using  pip can automatically resolve complex dependency issues and manage numerous packages easily with a single command.

Installing Packages

To install a package, you execute the pip command in the command prompt or terminal. Here is the basic command for installing a package:

pip install package_name

For example, to install a scientific computing package called NumPy, you would execute the following:

pip install numpy

Frequently Used Python Packages

NumPy

NumPy is a core package for numerical computation, providing high-performance multi-dimensional array objects and various mathematical functions. It is widely used in large-scale data analysis, machine learning, and simulations. Notably, it supports vectorized operations, allowing efficient data processing without loops.

Pandas

Pandas is a powerful tool for manipulating and analyzing data. By introducing a structure called a DataFrame, it enables data processing in a way similar to Excel. It is an essential package for filtering, aggregating data, and providing input and output in various formats.

Matplotlib

Matplotlib is a package used for visualizing data, allowing for the easy creation of line graphs, bar charts, histograms, and more. It supports various visualization options and is a useful tool for effectively conveying data analysis results.

TensorFlow

TensorFlow is an open-source machine learning platform developed by Google, used to build and train various types of deep learning models. It supports tensor and graph computations, making it a high-performance library for large-scale machine learning tasks.

Conclusion

In Python, packages are essential tools for systematically managing complex code. Packages enhance code readability, manage namespaces, and increase the reusability of modules. The installation and management of packages can be easily carried out through PyPI and pip, and leveraging the functionalities provided by various packages can maximize the power of Python. For these reasons, effective package management and utilization skills have become indispensable elements of modern Python programming.

Module of Python: A Powerful Tool for Programming

Python is a programming language that boasts amazing functionality and flexibility. The strength of this language is demonstrated through various modules, which play a key role in enhancing code reusability and reducing program complexity. In this post, we will delve deep into Python’s modules.

1. Definition and Purpose of Modules

In Python, a module is a file that collects related functions, classes, and variables. Modules maximize code reusability and facilitate easy code sharing among different programs. Specifically, utilizing modules offers the following benefits:

  • Repetition of functions that can easily be used in other programs.
  • Improved readability and maintainability of code.
  • Reduced size of executable files.
  • Performance improvements and error reduction through the compilation process.

1.1 Examples of Modules

The Python standard library includes numerous built-in modules. For instance, the math module provides a variety of mathematical functions such as trigonometric functions and logarithmic functions. Below is a simple example of using the math module:


import math

print(math.sqrt(16))  # Outputs 4.0
print(math.factorial(5))  # Outputs 120

2. How to Use Built-in Modules

Python’s built-in modules already implement commonly used functionalities. These modules are included by default with the Python installation, so no additional installation is required. Now, let’s look at some commonly used built-in modules.

2.1 os Module

The os module provides various functions to interact with the operating system. It allows for file path-related tasks and access to environment variables.


import os

# Get the current directory
current_directory = os.getcwd()
print("Current Directory:", current_directory)

# Create a new directory
os.mkdir("new_directory")

2.2 sys Module

The sys module provides information related to the Python interpreter. It is mainly used for processing command-line arguments.


import sys

# Print the received arguments
print("Received Arguments:", sys.argv)

# Python interpreter version information
print("Python Version:", sys.version)

2.3 datetime Module

The datetime module provides various classes to make date and time manipulation easy.


import datetime

# Print current date and time
now = datetime.datetime.now()
print("Current Date and Time:", now)

# Create a specific date
new_year = datetime.datetime(2023, 1, 1)
print("New Year's Day:", new_year)

3. Creating and Using Custom Modules

Creating a custom module is very straightforward. Simply create a Python file (.py) and define the required functions or variables inside it. You can then use this module in other Python files by using import.

3.1 Example of a Custom Module

Below is a simple example of a custom module:


# Filename: my_module.py

def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b

Save the above my_module.py file in the same directory, then use it in another script:


# Filename: main.py

import my_module

print(my_module.greet("Alice"))
print(my_module.add(3, 4))

In this way, you can modularize and reuse code through custom modules.

4. Installing and Using Third-Party Modules

The Python community provides countless third-party modules. These modules can generally be installed through the Python Package Index (PyPI). You can use the pip command to install them.

4.1 Installing Third-Party Modules

For example, to install the requests module, use the following command:

pip install requests

Using the requests module in Python code allows you to easily send network requests:


import requests

response = requests.get('https://api.github.com')
print(response.status_code)

By using these third-party modules, you can significantly extend the capabilities of Python.

5. Management of Modules and Best Practices

The best practices when using modules help create more maintainable code and prevent potential issues that may arise later.

5.1 Use Consistent Naming Conventions

Using consistent naming conventions increases the readability of modules and clarifies the functionalities provided by the module. PEP 8, the style guide for Python, recommends that module names be written in lowercase, with words separated by underscores.

5.2 Importance of Documentation

Thoroughly document the purpose and usage methods of modules and functions. This is particularly useful for other developers or for future reference, making it easy to understand and use the module.

5.3 Exception Handling

Effectively handle exceptions that may occur within the module to minimize potential errors during module usage. Actively utilize exception handling for this purpose.

5.4 Need for Testing

Write tests for the module to confirm that its functionalities work as expected. Testing is useful to ensure the module continues to operate correctly even after code changes.

In this way, Python modules play a crucial role in enhancing developer productivity and improving code quality. Understanding and using modules properly can lead to more efficient and cleaner code.

05-1 Python’s Classes

1. What is a Class?

A class is one of the basic units necessary for supporting object-oriented programming (OOP) in programming languages. A class is used to bundle data (attributes) and methods (functions) for manipulating that data together. Using classes allows you to organize the structure of your code well and make it more reusable.

2. Difference between Class and Object

A class is a blueprint (design) for creating objects. An object is an entity created based on a class, which occupies memory at runtime and has a state that can act.

3. Defining a Class

A class is defined using the class keyword. Class names usually start with an uppercase letter, and the body of the class should be indented.

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

4. Constructor and Destructor

A constructor is a method that is automatically called when an object is created, and it is mainly used to set the initial state of the object. In Python, the __init__ method serves this purpose. A destructor is called when an object is deleted and can be defined with the __del__ method.

5. Class Variables and Instance Variables

A class variable is a variable that is shared by the class, having the same value for all instances. An instance variable is a variable that can have separate values for each object.

class Car:
    number_of_wheels = 4  # Class variable

    def __init__(self, make, model, year):
        self.make = make    # Instance variable
        self.model = model  # Instance variable
        self.year = year    # Instance variable

6. Defining Methods

A method is a function defined within a class that defines the behavior of the object. Instance methods are usually used, and the first parameter is self, which allows access to the object itself.

class Car:
    def start_engine(self):
        print("Engine started")

7. Inheritance

Inheritance is a technique for creating new classes based on existing classes, which increases code reusability. It is defined in the form class DerivedClass(BaseClass):.

class ElectricCar(Car):
    def __init__(self, make, model, year, battery_size):
        super().__init__(make, model, year)
        self.battery_size = battery_size

8. Polymorphism

Polymorphism is the ability to handle different data types with the same interface. In Python, polymorphism can be implemented through method overriding.

class Animal:
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Woof!"

class Cat(Animal):
    def sound(self):
        return "Meow!"

9. Encapsulation

Encapsulation means restricting outside access to some of the implementation details of an object. In Python, it is conventionally indicated by prefixing the variable name with an underscore (private) to represent encapsulation.

10. Example of Using Classes

Here, we will create an example that includes all the concepts explained above.

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self._pages = pages  # Private variable

    def __str__(self):
        return f"{self.title} by {self.author}"

    def set_pages(self, pages):
        if pages > 0:
            self._pages = pages
        else:
            raise ValueError("The number of pages must be positive.")

Python Course: Chapter 04 Input and Output of Python

This course covers the input/output (I/O) system in Python in detail. I/O plays an important role in controlling the flow of data, enabling interaction between the user and the program, as well as connections with the file system. This chapter will cover a variety of Python input/output mechanisms, from basic console input/output methods to handling files and exception handling.

1. Console Input/Output

1.1 print() function

The most commonly used function for outputting to the console in Python is the print() function. This function allows you to print various types of data to the standard output device.

print("Hello, World!")

The code above prints “Hello, World!” to the console. The print() function can take multiple arguments and, by default, adds a space between them when printing.

print("Hello,", "Python!")

The code above prints “Hello, Python!”. The print() function provides options to easily customize the default printing behavior. For example, you can change the delimiter between outputs and the end of the output.

print("Python", "Programming", sep="-", end="!")

The code above prints “Python-Programming!”. The sep parameter specifies the separator between outputs, while the end parameter specifies the string to append at the end of the output.

1.2 input() function

The input() function is used to receive user input from the standard input device. The string that the user enters in the console is returned when the input() function ends. By default, all input is received in the form of strings.

name = input("Enter your name: ")
print("Hello,", name)

The code above prompts the user for their name and uses the entered name to output a greeting. If the entered data needs to be used as a numeric type, you must perform type conversion using the int() or float() functions.

age = int(input("Enter your age: "))
print("You are", age, "years old.")

The code above prompts for age input and uses it after converting to an integer.

2. File Input/Output

2.1 Opening a File

The way to open a file is by using the open() function. The open() function takes the filename and mode as arguments. The main modes are as follows:

  • 'r': Read mode
  • 'w': Write mode (overwrites existing file content)
  • 'a': Append mode (keeps existing content and adds new)
  • 'b': Binary mode (read/write binary files)

When a file is opened, a file object is created that allows file manipulation. Generally, after finishing file processing, you should call the close() method to close the file. This releases resources and prevents data loss.

file = open("example.txt", 'r')
content = file.read()
print(content)
file.close()

The code above opens the example.txt file in read mode, reads the file content, and prints it. Finally, the close() method is used to close the file.

2.2 Reading a File

There are several methods to read the contents of a file, and the following are the most commonly used methods:

  • read(): Reads the entire content of the file as a single string.
  • readline(): Reads a single line from the file. This includes the newline character.
  • readlines(): Returns a list containing each line of the file as an element.
file = open("example.txt", 'r')
line = file.readline()
while line:
    print(line, end='')
    line = file.readline()
file.close()

The code above reads and prints the file line by line. It reads each line until reaching the end of the file using a while loop. Since the newline character is included, the end parameter of the print() function is set to an empty string.

2.3 Writing to a File

To write data to a file, it needs to be opened in ‘w’ or ‘a’ mode. The ‘w’ mode overwrites the content of the file, while the ‘a’ mode adds content to the end of the existing file.

file = open("example.txt", 'w')
file.write("This is a new line.\n")
file.write("Writing to files is easy.\n")
file.close()

The code above erases the existing content of the file and adds two new lines. When writing to a file, the write() method is used, and ‘\n’ is explicitly included for line breaks.

2.4 Using with Statement for File I/O

Using the with statement for file I/O makes the code cleaner and prevents mistakes by automatically closing the file.

with open("example.txt", 'r') as file:
    content = file.read()
    print(content)

The code above opens the file using the with statement, and the file is automatically closed when exiting the with block. This provides the advantage of not needing to explicitly call the close() method.

3. File Modes and Binary Files

Unlike text files, binary files must be read and written using the ‘b’ mode. This is used for manipulating binary data such as images, audio, and video files.

with open("image.jpg", 'rb') as binary_file:
    binary_content = binary_file.read()

The code above opens an image file in binary mode and reads its contents. Similarly, ‘wb’ mode is used for writing files.

4. Exception Handling

When dealing with files, various exceptions can occur, such as when a file does not exist or there are no read permissions. Handling these exceptions can prevent abnormal termination of the program.

try:
    file = open("nonexistent_file.txt", 'r')
except FileNotFoundError:
    print("The file does not exist.")
finally:
    file.close()

The code above handles the FileNotFoundError when a file does not exist, informing the user that the file is missing. The finally block executes regardless of whether an exception occurred and is where resource cleanup can take place if needed.

When using the with statement, file closing is handled automatically, making exception handling somewhat simpler.

Conclusion

In this chapter, we covered various methods for input and output in Python. From the basics of console input/output to file input/output and exception handling, we learned how to effectively input and output data using Python. Since these I/O functions are crucial in nearly all Python programs, more practice and utilization are necessary.

In upcoming lectures, more advanced topics will be covered, so make sure to thoroughly understand and practice the content presented in this chapter.

04-4 Input and Output in Python, Input and Output of Programs

In this course, we will take a deep dive into input and output methods using Python. Input and output are fundamental elements of programming languages, providing the functionality to read and write data. In Python, various methods can be used for input and output, each with its unique use cases.

Standard Input/Output

Python outputs data to the standard output (console) through the print() function. This function is a basic way to display strings on the screen without additional specifications. The print() function can also accept one or more pieces of data separated by commas and allows for various formats to be specified, including newline characters.

print("Hello, Python!")  # Basic output
print("Name:", "Hong Gil Dong", "Age:", 25)  # Output multiple items

Conversely, to receive standard input, the input() function is used. It accepts user input as a string, enabling the design of dynamic programs. Data obtained using the input() function is always stored as a string, so it is essential to convert it into the appropriate data type as needed.

name = input("Please enter your name: ")  # User input
print("Hello,", name)  # Output the received data

File I/O

File I/O refers to the method of storing data in files or reading data from files. In Python, the open() function is used to open files, and data can be read and written using the methods of the file object. Files are typically opened in text mode but can also be opened in binary mode. File modes can be specified as read (‘r’), write (‘w’), append (‘a’), etc.

# Writing data to a file
with open("example.txt", "w") as file:
    file.write("Hello, world!")  # Write a string to the file

In the above example, the with statement is used to open the file. The with statement ensures that the file is opened, operations are performed, and the file is automatically closed afterward.

Here’s how to read data from a file:

# Reading data from a file
with open("example.txt", "r") as file:
    content = file.read()  # Read all content of the file
    print(content)

Understanding File Modes

There are various modes that can be used when opening files in Python. Each mode determines how the file will be handled.

  • r: Opens the file in read-only mode. An error occurs if the file does not exist.
  • w: Opens the file in write-only mode. If the file already exists, it will be overwritten.
  • a: Opens the file in append mode. If the file exists, data will be added at the end.
  • r+: Opens the file in read/write mode. The file must exist.
  • w+: Opens the file in read/write mode. If the file already exists, it will be overwritten.
  • a+: Opens the file in read/append mode. If the file exists, data will be added at the end.
  • b: Opens the file in binary mode.

Example: Reading Binary Files

When opening binary files (images, videos, etc.) instead of text files, Python provides powerful capabilities.

with open("example.jpg", "rb") as binary_file:
    data = binary_file.read()
    print("File size:", len(data), "bytes")  # Output the file size in bytes

Advanced I/O Techniques

Advanced Python input/output features include advanced usage of processing files in specific ways. For instance, handling CSV files or reading JSON files can be considered an expanded form of input and output.

CSV File Handling

Using Python’s csv module makes it easier to handle CSV files. CSV files are a simple file format that stores data separated by commas (`,`).

import csv

# Writing to a CSV file
with open("data.csv", "w", newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 25])
    writer.writerow(["Bob", 30])

# Reading from a CSV file
with open("data.csv", "r") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

JSON File Handling

JSON serves as a means to handle JavaScript object notation in Python. Python’s json module provides functionality to convert JSON format into Python data types and vice versa.

import json

# Writing JSON data
data = {
    "name": "Charlie",
    "age": 35,
    "city": "Seoul"
}

with open("data.json", "w") as jsonfile:
    json.dump(data, jsonfile)

# Reading JSON data
with open("data.json", "r") as jsonfile:
    data_loaded = json.load(jsonfile)
    print(data_loaded)

NOTE: JSON and CSV are widely used for data exchange on the web. It is crucial to handle data in the correct format to minimize risks.

Character Encoding and Decoding

When performing input and output, it is important to properly set character encoding and decoding. Particularly in programs that support multiple languages, using UTF-8 is common.

# Writing a UTF-8 encoded file
with open("utf8_file.txt", "w", encoding="utf-8") as file:
    file.write("Hello. This is a UTF-8 encoded file.")

# Reading a UTF-8 encoded file
with open("utf8_file.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

If encoding is not specified, Python will follow the default settings of the individual operating system. This can cause compatibility issues when using files on different systems. Therefore, it is always recommended to specify the encoding explicitly.

Conclusion

Python provides powerful and flexible input/output capabilities. The input/output process does not just end with displaying simple data on the screen or reading from files; it includes methods for reading and writing various formats of data. Understanding and handling standard input/output to file I/O, as well as file modes, are all essential skills.

Continue to practice various input/output methods and applications to expand your programming skills. In the next session, we will take a closer look at exception handling in Python. If you have any questions, feel free to leave a comment!