Python Exception Handling, JSON Processing, Data Visualization, OOP, and MySQL Integration

Exceptino Handling

# Basic structure for catching errors
try:
    # Code that might raise an error
except:
    # Code to run if an error occurs

# Handling a specific error type
try:
    print(undefined_var)
except NameError as error_msg:
    print("Caught an undefined variable error")
    print(error_msg)

# Handling multiple potential errors
try:
    print(10 / 0)
except (NameError, ZeroDivisionError) as error_msg:
    print(error_msg)

# Catching any exception
try:
    print(undefined_var)
except Exception as error_msg:
    print(error_msg)
else:
    # Runs if no exception occurs
    print("Execution completed without errors")
finally:
    # Always runs, typically for cleanup
    print("Process finished")

# Exceptions propagate upwards through the call stack

Working with JSON

import json

# JSON acts as an intermediate format for data exchange between languages
# In Python, JSON often maps to dictionaries or lists of dictionaries

data_records = [{"name": "Li Tang Dingzhen", "age": 23}, {"name": "Cheese Snow Leopard", "age": 0}]

# Convert Python object to JSON string
json_output = json.dumps(data_records, ensure_ascii=False)
print(type(json_output))
print(json_output)
print("--------------")

# Convert JSON string back to Python object
json_input = '[{"name": "Li Tang Dingzhen", "age": 23}, {"name": "Cheese Snow Leopard", "age": 0}]'
python_data = json.loads(json_input)
print(type(python_data))
print(python_data)

Cerating Bar Charts with Pyecharts

from pyecharts.charts import Bar
from pyecharts.options import LabelOpts

chart = Bar()
chart.add_xaxis(["China", "USA", "UK"])
chart.add_yaxis("GDP", [30, 20, 10], label_opts=LabelOpts(position="right"))
chart.reversal_axis()
chart.render("bar_chart.html")

Building Line Charts

from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LegendOpts, ToolboxOpts, VisualMapOpts

line_chart = Line()
line_chart.add_xaxis(["China", "USA", "UK"])
line_chart.add_yaxis("GDP", [30, 20, 10])

line_chart.set_global_opts(
    title_opts=TitleOpts(title="GDP Comparison", pos_left="center", pos_bottom="1%"),
    legend_opts=LegendOpts(is_show=True),
    toolbox_opts=ToolboxOpts(is_show=True),
    visualmap_opts=VisualMapOpts(is_show=True)
)

line_chart.render("line_chart.html")

Rendering Geographcial Maps

from pyecharts.charts import Map
from pyecharts.options import VisualMapOpts

geo_map = Map()
region_data = [
    ("Beijing", 99),
    ("Shanghai", 9),
    ("Jiangxi", 99999),
    ("Yunnan", 599),
    ("Guangdong", 499)
]

geo_map.add("Test Map", region_data, "china")
geo_map.set_global_opts(
    visualmap_opts=VisualMapOpts(
        is_show=True,
        is_piecewise=True,
        pieces=[
            {"min": 1, "max": 9, "label": "1-9", "color": "#CCFFFF"},
            {"min": 10, "max": 99, "label": "10-99", "color": "#FFFF99"},
            {"min": 100, "max": 499, "label": "100-499", "color": "#FF9966"},
            {"min": 500, "max": 999, "label": "500-999", "color": "#FF6666"},
            {"min": 1000, "max": 9999, "label": "1000-9999", "color": "#CC3333"},
            {"min": 10000, "label": "10000+", "color": "#990033"}
        ]
    )
)
geo_map.render("map_chart.html")

Object-Oriented Programming: Classes

import random

# Basic class definition
class Person:
    name = None
    age = None

    def introduce(self):
        print(f"Hello, I am {self.name}")

p1 = Person()
p1.name = "Dingzhen Zhenzhu"
p1.age = 23
p1.introduce()

# Constructor and magic methods
class PersonInfo:
    def __init__(self, name, age, phone):
        self.name = name
        self.age = age
        self.phone = phone

    def __str__(self):
        return f"Person: {self.name}, Age: {self.age}"

    def __lt__(self, other):
        return self.age < other.age

    def __eq__(self, other):
        return self.age == other.age

person_a = PersonInfo("Nicotine Zhen", 23, 13879694754)
person_b = PersonInfo("Cheese Leopard", 5, 0)
print(person_a)
print(person_a < person_b)
print(person_a == person_b)

# Encapsulation
class Smartphone:
    __internal_id = None

    def __make_call(self):
        print("Calling...")

# Inheritance
class BaseClass:
    def greet(self):
        print("Hello from Base")

class DerivedClass(BaseClass):
    pass

obj = DerivedClass()
obj.greet()

# Method overriding
class Parent:
    def action(self):
        print("Parent action")

class Child(Parent):
    def action(self):
        super().action()
        print("Child action")

child_obj = Child()
child_obj.action()

Type Annotations

# Variable annotations
id_num: int = 24
user_name: str = "Kobe"
is_active: bool = True

class User:
    pass

user_obj: User = User()

# Container annotations
int_list: list[int] = [1, 2, 3]
mixed_tuple: tuple[int, str, bool] = (1, "what", True)
str_dict: dict[str, int] = {"score": 100}

# Function annotations
from typing import Union

def process_data(value: Union[int, str]) -> Union[int, str]:
    pass

Polymorphism

class BaseAnimal:
    def make_sound(self):
        pass

class Doggy(BaseAnimal):
    def make_sound(self):
        print("woof woof")

class Kitty(BaseAnimal):
    def make_sound(self):
        print("meow meow")

def animal_sound(animal: BaseAnimal):
    animal.make_sound()

dog = Doggy()
cat = Kitty()
animal_sound(dog)
animal_sound(cat)

MySQL Operations

-- Database operations
SHOW DATABASES;
USE world;
CREATE DATABASE test_db CHARSET utf8;
DROP DATABASE test_db;
SELECT DATABASE();

-- Table operations (DDL)
SHOW TABLES;
CREATE TABLE students(
    id INT,
    name VARCHAR(10),
    age INT
);
DROP TABLE students;

-- Data manipulation (DML)
INSERT INTO students (id, name, age) VALUES (1, 'Paul', 29);
DELETE FROM students WHERE id <= 4;
UPDATE students SET name = 'Updated' WHERE id = 1;

-- Data querying (DQL)
SELECT name FROM students;
SELECT * FROM students WHERE age = 29;
SELECT gender, AVG(age) FROM students GROUP BY gender;
SELECT * FROM students ORDER BY age ASC LIMIT 5;

Interacting with MySQL using Python

from pymysql import Connection

# Establish connection
db_conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='123456',
    autocommit=True
)

# Execute a query
cursor = db_conn.cursor()
db_conn.select_db("test_db")
cursor.execute("SELECT * FROM students")
query_results = cursor.fetchall()
for row in query_results:
    print(row)

# Insert data
cursor.execute("INSERT INTO students VALUES (1, 'Gangben', 18)")

# Close connection
db_conn.close()

Tags: python Exception Handling JSON pyecharts Object-Oriented Programming

Posted on Fri, 26 Jun 2026 16:01:38 +0000 by roygbiv