100 Classic Python Programming Cases with Source Code

The Python programming language, with its simple syntax and powerful libraries, has become a tool for beginners and developers to quickly realize their ideas. This article compiles a set of 100 classic cases covering core Python knowledge points and typical application scenarios, helping readers enhance their programming skills through practice. The following sections will select some representative cases for analysis from dimensions such as basic syntax, data processing, algorithm implementation, and project development, along with some source code examples.

100 Classic Python Programming Cases with Source Code

1. Basic Syntax and Logic Training

Beginners can master core Python syntax through basic cases. For example, a temperature conversion program (Celsius to Fahrenheit) can be implemented in just 3 lines of code:

Copy

celsius = float(input("Enter Celsius temperature: "))
fahrenheit = (celsius * 9/5) + 32
print(f"Fahrenheit temperature is: {fahrenheit:.1f}F")

This type of case focuses on training input/output and arithmetic operations. Similar cases include a simple calculator, a number guessing game (using the random module to generate random numbers), and generating the Fibonacci sequence. The prime number judgment program demonstrates the combined application of loops and conditional statements:

Copy

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

2. Data Structure Operation Cases

The efficient use of built-in data structures in Python is key to development. The linked list implementation case demonstrates the creation and traversal methods of a node class:

Copy

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
class LinkedList:
    def __init__(self):
        self.head = None
    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        last = self.head
        while last.next:
            last = last.next
        last.next = new_node

Other typical data structure cases include binary tree traversal, stack and queue implementations, and hash table applications. For example, using a dictionary to implement a student grade management system, storing and querying data through key-value pairs.

3. File and Data Processing

File operation cases help master data persistence capabilities. The text word frequency statistics program demonstrates file reading and dictionary counting:

Copy

from collections import defaultdict

def word_count(file_path):
    counts = defaultdict(int)
    with open(file_path, 'r') as f:
        for line in f:
            words = line.strip().split()
            for word in words:
                counts[word] += 1
    return dict(counts)

Advanced cases involve CSV/Excel data processing, such as using the pandas library for data cleaning:

Copy

import pandas as pd

def clean_data(input_file):
    df = pd.read_csv(input_file)
    df.dropna(inplace=True)
    df['Date'] = pd.to_datetime(df['Date'])
    return df[df['Sales'] > 1000]

4. Network and Web Scraping Applications

The Requests library network request case is fundamental to web scraping development. The following code retrieves webpage content:

Copy

import requests

def fetch_url(url):
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        print(f"Request exception: {e}")
        return None

Combining HTML parsing cases with BeautifulSoup can extract specific data. For example, scraping news titles:

Copy

from bs4 import BeautifulSoup

def parse_titles(html):
    soup = BeautifulSoup(html, 'html.parser')
    return [h1.text for h1 in soup.find_all('h1', class_='news-title')]

5. Algorithms and Mathematical Problems

Classic algorithm cases include the implementation of sorting algorithms. Here is an example of quicksort:

Copy

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

Mathematical problems such as finding the greatest common divisor (GCD):

Copy

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

6. Project-Level Development Cases

Comprehensive application cases cover web development, GUI programs, etc. An example of building an API interface with Flask:

Copy

from flask import Flask, jsonify

app = Flask(__name__)
@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify([{ "id": 1, "name": "item1" }, { "id": 2, "name": "item2" }])

GUI development cases can use Tkinter to create a simple text editor:

Copy

import tkinter as tk
from tkinter.filedialog import asksaveasfilename

class TextEditor:
    def __init__(self):
        self.root = tk.Tk()
        self.text = tk.Text(self.root)
        self.text.pack()
        tk.Button(self.root, text="Save", command=self.save_file).pack()
    def save_file(self):
        path = asksaveasfilename()
        if path:
            with open(path, 'w') as f:
                f.write(self.text.get("1.0", "end"))

The above cases cover the core application scenarios of Python programming. The complete set of 100 cases includes more advanced content such as machine learning model training, asynchronous programming practices, and automation operation scripts. Each case provides a complete runnable source code file, and it is recommended that readers debug the code line by line in their local environment, deepening their understanding by modifying parameters and extending functionality. Improving programming skills requires continuous practice, and these classic cases can serve as an important reference on the learning journey.

Leave a Comment