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!

Input and Output in Python: File Reading and Writing

Introduction

File input and output are essential elements in most programming languages, used for permanently storing data or importing external data into a program. Python provides powerful and intuitive features for easily performing these file input and output operations. In this tutorial, we will explain in detail how to read and write files using Python.

Opening and Closing Files

The first thing to do when working with files is to open the file in Python. To open a file, we use the built-in function open(). The open() function takes the file name and the file opening mode as parameters.

file_object = open("example.txt", "r") # Open file in read mode

After using the file, it must be closed. This releases system resources and prevents data corruption. Closing a file can be done using the close() method.

file_object.close()

File Opening Modes

When opening a file, various modes can be used depending on the file’s purpose. The main file opening modes are as follows:

  • 'r': Read mode. Used to read the contents of the file. The file must exist.
  • 'w': Write mode. Used to write content to the file. If the file does not exist, a new file is created, and if the existing file exists, all contents are deleted.
  • 'a': Append mode. Used to append content to the end of the file. If the file does not exist, a new file is created.
  • 'b': Binary mode. Used for handling files in binary. For example, ‘rb’ is binary read mode.
  • 't': Text mode. The default, processes as a text file.
  • 'x': Exclusive creation mode. Creates a new file only if it does not exist. If the file already exists, an error occurs.

Reading Files

The process of reading files is mainly done through the methods read(), readline(), and readlines(). Depending on the file size and format, you can choose the appropriate method to use.

The read() Method

The read() method reads the contents of the file as a string. It can read the entire file content at once, or specify the number of bytes to read, and after the read operation, the file pointer will be positioned at the end of the file.

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

The readline() Method

The readline() method is useful for reading one line at a time. The newline character at the end of the line is included, and after the read operation, the file pointer moves to the next line.

with open("example.txt", "r") as file:
    line = file.readline()
    while line:
        print(line, end='')
        line = file.readline()

The readlines() Method

The readlines() method reads all lines from the file and returns them as a list. Each line is treated as an individual element in the list.

with open("example.txt", "r") as file:
    lines = file.readlines()
for line in lines:
    print(line, end='')

Writing Files

The process of writing content to a file is done through the methods write() and writelines(). These methods provide various ways to write data to the file, allowing for flexibility in use.

The write() Method

The write() method writes string data to a file. After writing data, you must call flush() or close the file to ensure the data is actually written.

with open("example.txt", "w") as file:
    file.write("Hello, World!")

The writelines() Method

The writelines() method takes a list of strings and writes them to the file. Each string is appended to the end of the existing line, so you may need to explicitly add newline characters at the end of each string.

with open("example.txt", "w") as file:
    lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
    file.writelines(lines)

Exception Handling for File Processing

File operations can encounter various errors, so it is important to manage exceptions effectively. You can manage exceptions using Python’s tryexcept statement, which allows you to handle exceptions such as file not found, read errors, and more.

try:
    with open("example.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("The file does not exist.")
except Exception as e:
    print(f"An exception occurred: {e}")

Conclusion

In this tutorial, we covered the basic ways to read and write files in Python, the main methods, and how to manage exceptions during file processing. File input and output are essential functions for exchanging and storing application data with the outside world. By utilizing various file input and output methods and proper exception handling, you can write more robust Python programs.

python course: Input and Output of Python, User Input and Output

Python is a powerful programming language that provides functionalities for handling input and output of data very easily. In this course, we will explore the basic input and output mechanisms provided by Python and how to handle user input in depth. Through this, you will be equipped to create applications that interact directly with data.

Standard Input and Output in Python

To understand input and output in Python, we should start with the most basic functions. The print() and input() functions are used very frequently in Python programming. The print() function is used to display output in the console, while the input() function is used to receive user input.

print() Function

The print() function is used for visualizing data. For example, it can be used to check the value of a variable or to monitor the status of a program.

# Output Hello, World!
print("Hello, World!")

In the above code, the string "Hello, World!" is printed to the console. The print() function can output various types of data and can take multiple arguments separated by commas.

a = 5
b = "Python Programming"
print(a, b)

In the above code, the number 5 and the string “Python Programming” are printed, separated by a space. The print() function can also flexibly adjust the formatting of the output through additional parameters. For example, it can change the delimiter between printed items or append additional strings at the end.

print(a, b, sep=", ", end="!!\n")

In this case, the output will appear as “5, Python Programming!!”, where each element is separated by a comma and space, and “!!” is added at the end.

input() Function

The input() function is used to receive user input. This function processes the input as a string, hence, if you want to receive a number, you need to perform type conversion.

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

In the above example, when the user inputs their name, it uses that name to print “Hello, [Name]”. You should remember that everything the user inputs is processed as a string.

Advanced Output Formatting

There are various ways to format output, and to enhance readability and flexibility, Python supports multiple output formatting options.

Basic String Formatting

The traditional method of using Python’s basic string formatting involves using the % symbol within a string to indicate where a variable should appear, and then assigning the variable to that placeholder.

age = 30
print("I am %d years old." % age)

This method can also include multiple items using tuples.

name = "Cheolsu"
age = 30
print("%s is %d years old." % (name, age))

However, this method can be somewhat restrictive and less readable compared to modern alternatives.

str.format() Method

From Python 2.7 and 3.2 onwards, you can use the str.format() method for formatting. This method involves placing {} symbols where you want the variables, and passing the corresponding values as arguments to the format() method.

print("{} is {} years old.".format(name, age))

You can also specify the indexes for clarity on which values should appear in which positions.

print("{0} is {1} years old.".format(name, age))

This method is more readable and provides the advantage of easily modifying the order of variables or output format.

Python 3.6 and f-strings

From Python 3.6 onwards, you can use f-strings. This method involves prefixing the string with f and directly placing variables within curly braces, making it very intuitive and the code more concise.

print(f"{name} is {age} years old.")

This method offers great readability and the advantage of directly inserting variables. Additionally, it supports embedded expressions to easily apply complex data transformations or calculations.

Advanced User Input Handling

Handling user input encompasses more than just receiving it; it involves validating the input, providing appropriate feedback, and requesting re-input from the user if necessary.

Type Conversion and Exception Handling

The input() function always returns a string, so if you need other data types like numbers, conversion is necessary. Exception handling is required to manage potential errors that may occur during this process.

try:
    age = int(input("Please enter your age: "))
    print(f"Your age is {age}.")
except ValueError:
    print("Please enter a valid number.")

In the above code, if the user inputs a non-numeric value, a ValueError will be raised, and a friendly error message will be displayed while keeping the program safe.

Repeating Until Valid Input is Received

You can continuously request valid input from the user until they provide it. This is implemented by requiring input until certain conditions are met.

while True:
    try:
        age = int(input("Please enter your age: "))
        break  # Stop repeating on valid input
    except ValueError:
        print("Please enter a valid number.")

print(f"The age entered is {age}.")

This iterative structure provides the user with the opportunity to correct invalid input while maintaining the normal flow of the program.

Conclusion

In this tutorial, we have learned the basic input and output methods in Python, as well as various techniques for handling user input. Through this, you have likely gained knowledge on how to enhance the flexibility and safety of your programs. In the next tutorial, we will explore more complex data processing techniques such as file input and output.

If you have any questions or need assistance in the meantime, please feel free to ask in the comments section below. Happy coding!