3.0 Basic Python Programming for Daily Tasks

Zero, Introduction: Programming is like snacking on sunflower seeds, once you start, you can’t stop!

Friends, today let’s talk about something practical! Python is like our family heirloom kitchen knife; it can chop dumpling filling and is also great for smashing cucumbers. I’ll teach you the most basic syntax to handle those daily chores, saving you time to snack on more sunflower seeds, right?

1. Automatically Organizing Your Phone Gallery (File Operations)

1. Check the current state of the gallery

Your phone gallery is currently a mess, like my storage room: photos of skewers, selfies in the snow, and a hundred-day celebration of relatives’ kids all mixed together, making it hard to find a picture. Let’s use Python to automatically categorize them!

import os
import shutil
# Define the classification rules for what type of photos go where
classification_rules = {
    "Skewers": ["BBQ", "Grilled Meat", "Liver"],
    "Snow Scenes": ["Snowman", "Sledding", "Rime"] ,
    "Relatives": ["Uncle", "Aunt", "Full Moon Feast"]
}

def organize_gallery(original_folder="Phone Gallery", new_folder="Organized Gallery"):
    # Check each file one by one
    for filename in os.listdir(original_folder):
        # Skip hidden files (like peeling garlic, we don't need the skin)
        if filename.startswith('.'): 
            continue
        found_category = False
        # Compare which category the photo belongs to
        for category_name, keywords in classification_rules.items():
            for keyword in keywords:
                if keyword in filename:
                    target_path = os.path.join(new_folder, category_name)
                    # Create the category if it doesn't exist (like clearing out a drawer)
                    if not os.path.exists(target_path):
                        os.makedirs(target_path)
                    # Move the file like rearranging furniture
                    shutil.move(os.path.join(original_folder, filename), target_path)
                    found_category = True
                    break
            if found_category:
                break
        # If no match, throw it in the "Others" bin
        if not found_category:
            other_path = os.path.join(new_folder, "Others")
            if not os.path.exists(other_path):
                os.makedirs(other_path)
            shutil.move(os.path.join(original_folder, filename), other_path)

organize_gallery()

Key Explanation:

<span>os</span> module is like your flashlight, shining wherever you look<span>shutil.move()</span> is like telling your kids to do chores: “Go! Move this to that room!”

2. Family Income and Expense Ledger (Data Storage)

1. Say goodbye to messy accounts

At the end of each month, looking at the WeChat balance leaves me confused: “Why does the money disappear like spring snow?” Let’s create an automatic ledger:

import csv
from datetime import datetime

def record_expense(amount, category, note=""):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
    # Opening the ledger is like lifting a curtain
    with open("family_ledger.csv", "a", newline="", encoding="utf-8") as file:
        ledger_writer = csv.writer(file)
        ledger_writer.writerow([timestamp, amount, category, note])
    print(f"Recorded: {timestamp} spent {amount} on {category}, note: {note or 'Nothing to say'}")

# Example usage
record_expense(150, "Food", "Liu's family pig slaughter dish for three")
record_expense(88, "Clothing", "Buy one get one free big cotton shoes")

2. Checking accounts is easier than flipping a mattress

import pandas as pd

def monthly_summary():
    ledger = pd.read_csv("family_ledger.csv", names=["Time", "Amount", "Category", "Note"])
    ledger["Time"] = pd.to_datetime(ledger["Time"])
    this_month_data = ledger[ledger["Time"].dt.month == datetime.now().month]
    print("Top 3 expenses this month:")
    print(this_month_data.sort_values("Amount", ascending=False).head(3))
    print("\nCategory statistics:")
    print(this_month_data.groupby("Category")["Amount"].sum())

monthly_summary()

Attention, friends:

<span>csv.writer</span> is like a family ledger, every stroke must be accurate<span>pandas</span> is like a big abacus, it can straighten out even the most chaotic numbers

3. Timed Reminders for Household Chores (Time Module)

1. Say goodbye to nagging from your wife

Always forgetting to water the plants, feed the chickens, or take out the trash? Let’s create a reminder program, better than an alarm clock!

import time
from win10toast import ToastNotifier

reminder = ToastNotifier()
chores_list = [
    ("Feed the geese", 3600),  # Every hour
    ("Wipe the mattress", 7200),  # Every 2 hours
    ("Turn the sauerkraut jar", 14400)  # Every 4 hours
]
print("Starting to monitor chores, press Ctrl+C to stop")
try:
    while True:
        for task, interval in chores_list:
            reminder.show_toast("Hey, pay attention!", f"It's time to {task}!", duration=10)
            time.sleep(interval)
except KeyboardInterrupt:
    print("That's it for today, let the neighbor Wang keep an eye on the rest")

Installation Reminder: First, run <span>pip install win10toast</span>, just like laying a mattress, you need to prepare the base first

4. Automatically Generating Shopping Lists (String Processing)

1. Say goodbye to the embarrassment of forgetting to bring soy sauce

Every time I go to the market, I forget to buy two or three items; let’s create a program to help you remember:

def generate_shopping_list(common_items=None):
    # Default list is like a storage cabinet at home
    base_list = {
        "Grocery Store": ["Soy Sauce", "Noodles", "Dried Chili"],
        "Vegetable Market": ["Cabbage", "Potato", "Green Onion"],
        "Convenience Store": ["Lighter", "Playing Cards", "Old Snowflake"]
    }
    # Allow customization like adding ingredients to a dish
    if common_items:
        for store, items in common_items.items():
            base_list[store].extend(items)
    # Generate the list like slicing sauerkraut, it needs to be neat
    print("★"*20 + " Shopping List " + "★"*20)
    for store, items in base_list.items():
        print(f"\n[{store}] To buy:")
        for number, item in enumerate(items, 1):
            print(f"{number}. {item}", end="  ")
    print("\n" + "★"*50)

# Example usage
generate_shopping_list({"Hardware Store": ["Wire Mesh", "Nails"]})

5. Automatically Replying to WeChat Messages (API Call)

1. Dealing with greetings from distant relatives

During the New Year, WeChat messages flood in? Let’s create an intelligent reply:

import requests

def auto_reply(received_message):
    # Call the Qingyunke intelligent reply (free API)
    reply_content = requests.get(f"http://api.qingyunke.com/api.php?key=free&amp;appid=0&amp;msg={received_message}").json()["content"]
    # Translate the robot's reply into local dialect
    local_reply = reply_content.replace("Mom", "Our Mom").replace("Dad", "Our Dad").replace("Hello", "What's up")
    return local_reply

# Simulate receiving messages
messages = ["Are you there? Help me chop something!", "When are you having kids?", "I'll introduce you to someone!"]
for message in messages:
    print(f"Received message: {message}")
    print(f"Auto reply: {auto_reply(message)}\n")

Effect Display:

Received message: Are you there? Help me chop something!  Auto reply: What's up, I'm studying, can't help you for now!  
Received message: When are you having kids?  Auto reply: This matter needs to be asked to our parents, they decide!

6. Key Technical Summary

1.File Operations: Like organizing a storage room, you need to know where everything goes2.Scheduled Tasks: More effective than an alarm clock, like having a little secretary3.External Interfaces: Like sending the neighbor’s kid on errands, you don’t have to do everything yourself4.Error Handling: Like having a band-aid ready, just in case

7. Next Episode Preview

Next time we’ll cover “Using Python to Improve Rural Living Standards”, teaching you how to:

1.Monitor the temperature of the firewood stove and automatically remind to add wood2.Analyze the humidity of the vegetable garden and automatically control watering3.Generate drying guidelines based on weather forecasts

If you feel it’s useful, quickly set up a second-hand computer! Remember, programming is like pickling cabbage, the longer it sits, the better it gets. If you have any questions, come to my place, and we can chat slowly while roasting corn!

Leave a Comment