Python Tutorial

OOP, Files and Exceptions

Use classes, objects, file handling and exception handling to build more realistic Python programs.

Concept

A class defines data and behavior that belong together. Instances are objects created from that class. OOP is useful when a problem naturally contains entities with state and actions.

File handling persists data beyond one program run. Exceptions let you handle expected failures such as missing files or invalid user input without crashing the whole program.

Example

class Course:
    def __init__(self, name):
        self.name = name

    def label(self):
        return f"Course: {self.name}"

course = Course("Python")
print(course.label())
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.

Practice Tasks

  1. Create a Student class with name and course fields.
  2. Write three lines to a text file and read them back.
  3. Catch ValueError when converting invalid text to an integer.

Key Takeaways

  • Classes group related state and behavior.
  • Use with open(...) for safe file handling.
  • Catch specific exceptions rather than hiding every error.