Fundamentals 8 min read

Master Python Basics: Error Handling, Files, OOP, and More

This guide walks through essential Python concepts—including try/except error handling, file reading and writing, class definitions with inheritance, variable scopes, common built‑in functions, docstrings, comments, and command‑line argument processing—providing clear code examples for each topic.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Master Python Basics: Error Handling, Files, OOP, and More

Error Handling and Exceptions

Python uses try, except, and optional finally blocks to manage runtime errors. Specific exception types (e.g., ZeroDivisionError, ValueError) can be caught, and finally runs regardless of whether an exception occurred.

try:
    # Code that may raise an exception
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
try:
    result = int(input("Enter a number: "))
    print(result)
except ValueError:
    print("Invalid input! Please enter a valid integer.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"An error occurred: {e}")
try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    if file:
        file.close()

File Operations

Reading and writing files is performed with the built‑in open function, typically inside a with context manager to guarantee proper closure.

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

# Reading line by line
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())
# Writing text (overwrites existing file)
with open("output.txt", "w") as file:
    file.write("Hello, world!
")
    file.write("This is a test.
")

# Appending text
with open("output.txt", "a") as file:
    file.write("Appending more text.
")

Classes and Objects

Define a class with the class keyword, implement an __init__ constructor, and add methods. Inheritance is expressed by listing a parent class in parentheses.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def introduce(self):
        print(f"My name is {self.name} and I am {self.age} years old.")

alice = Person("Alice", 25)
alice.introduce()
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade
    def study(self):
        print(f"{self.name} is studying.")

bob = Student("Bob", 20, "A")
bob.introduce()
bob.study()

Namespaces and Scope

Variables defined inside a function are local to that function. The global keyword allows a function to modify a variable defined at module level.

# Local scope example
def my_function():
    x = 10
    print(x)  # 10
my_function()
# print(x)  # NameError: x is not defined
# Global scope example
x = 10

def my_function():
    global x
    x = 20
    print(x)  # 20
my_function()
print(x)  # 20

Common Built‑in Functions

Python provides a rich set of built‑in utilities for type conversion, string manipulation, list handling, and dictionary operations.

Type conversion: str(10), int("10"), float("10.5"), bool(0), bool(1) String operations: len("hello"), "HELLO".lower(), "hello".upper(), "hello world".split(" "), " ".join(["hello", "world"]) List operations: my_list.append(10), my_list.remove(10), my_list.sort(), my_list.reverse() Dictionary operations: my_dict.keys(), my_dict.values(),

my_dict.items()

Docstrings and Comments

Triple‑quoted strings placed immediately after a function definition become the function’s docstring, describing purpose, arguments, and return value. Single‑line comments start with #; multi‑line comments can also use triple quotes.

def add(a, b):
    """
    Add two numbers and return the result.

    Args:
        a (int): First operand.
        b (int): Second operand.

    Returns:
        int: Sum of a and b.
    """
    return a + b

help(add)  # Displays the docstring

# Single‑line comment example
x = 10  # assign a value

"""Multi‑line comment example.
It can span several lines.
"""

Command‑Line Arguments

Scripts often need to accept parameters from the command line. The sys.argv list contains the script name followed by any supplied arguments.

import sys
print(sys.argv)  # Shows the argument list

if len(sys.argv) != 3:
    print("Usage: script.py <input_file> <output_file>")
    sys.exit(1)

input_file = sys.argv[1]
output_file = sys.argv[2]

# Read the input file
with open(input_file, "r") as file:
    content = file.read()

# Write to the output file
with open(output_file, "w") as file:
    file.write(content)

These fundamentals form a solid base for building more complex Python applications, such as automated testing, data processing, and web development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonfile I/Ocommand-lineError HandlingOOPbuilt-in functionsDocstrings
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.