Book Tracker

 import sqlite3

from tkinter import Tk, Label, Entry, Button, ttk, messagebox


# Database setup

def setup_database():

    conn = sqlite3.connect('books.db')

    cursor = conn.cursor()

    cursor.execute("""

        CREATE TABLE IF NOT EXISTS books (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            title TEXT NOT NULL,

            author TEXT NOT NULL,

            status TEXT NOT NULL

        )

    """)

    conn.commit()

    conn.close()


# Add book

def add_book(title, author, status):

    if not title or not author or not status:

        messagebox.showerror("Error", "All fields are required.")

        return

    conn = sqlite3.connect('books.db')

    cursor = conn.cursor()

    cursor.execute("INSERT INTO books (title, author, status) VALUES (?, ?, ?)", (title, author, status))

    conn.commit()

    conn.close()

    messagebox.showinfo("Success", "Book added successfully!")

    refresh_list()


# Get books

def get_books():

    conn = sqlite3.connect('books.db')

    cursor = conn.cursor()

    cursor.execute("SELECT id, title, author, status FROM books")

    books = cursor.fetchall()

    conn.close()

    return books


# Update book status

def update_status(book_id, new_status):

    conn = sqlite3.connect('books.db')

    cursor = conn.cursor()

    cursor.execute("UPDATE books SET status = ? WHERE id = ?", (new_status, book_id))

    conn.commit()

    conn.close()

    messagebox.showinfo("Success", "Book status updated successfully!")

    refresh_list()


# Delete book

def delete_book(book_id):

    conn = sqlite3.connect('books.db')

    cursor = conn.cursor()

    cursor.execute("DELETE FROM books WHERE id = ?", (book_id,))

    conn.commit()

    conn.close()

    messagebox.showinfo("Success", "Book deleted successfully!")

    refresh_list()


# Refresh the book list in the GUI

def refresh_list():

    for row in tree.get_children():

        tree.delete(row)

    books = get_books()

    for book in books:

        tree.insert("", "end", values=book)


# GUI setup

def setup_gui():

    global tree

    root = Tk()

    root.title("Book Tracker")


    # Labels and input fields

    Label(root, text="Title:").grid(row=0, column=0, padx=5, pady=5)

    title_entry = Entry(root)

    title_entry.grid(row=0, column=1, padx=5, pady=5)


    Label(root, text="Author:").grid(row=1, column=0, padx=5, pady=5)

    author_entry = Entry(root)

    author_entry.grid(row=1, column=1, padx=5, pady=5)


    Label(root, text="Status:").grid(row=2, column=0, padx=5, pady=5)

    status_combobox = ttk.Combobox(root, values=["To Read", "Reading", "Finished"])

    status_combobox.grid(row=2, column=1, padx=5, pady=5)


    # Buttons

    Button(root, text="Add Book", command=lambda: add_book(title_entry.get(), author_entry.get(), status_combobox.get())).grid(row=3, column=0, columnspan=2, pady=10)


    # Book list

    columns = ("ID", "Title", "Author", "Status")

    tree = ttk.Treeview(root, columns=columns, show="headings")

    for col in columns:

        tree.heading(col, text=col)

        tree.column(col, width=150)

    tree.grid(row=4, column=0, columnspan=2, padx=5, pady=5)


    # Actions

    Button(root, text="Update Status", command=lambda: update_status(tree.item(tree.focus())['values'][0], status_combobox.get())).grid(row=5, column=0, pady=10)

    Button(root, text="Delete Book", command=lambda: delete_book(tree.item(tree.focus())['values'][0])).grid(row=5, column=1, pady=10)


    refresh_list()

    root.mainloop()


if __name__ == "__main__":

    setup_database()

    setup_gui()


Python is TIOBE's programming language of the year 2024!

 TIOBE Index for January 2025

January Headline: Python is TIOBE's programming language of the year 2024!

Programming language Python has won the title "TIOBE's programming language of the year 2024". This award is given to the programming language with the highest increase in ratings in one year time. Python gained a whopping 9.3% in 2024. This is far ahead of its competition: Java +2.3%, JavaScript +1.4% and Go +1.2%. Python is everywhere nowadays, and it is the undisputed default language of choice in many fields. It might even become the language with the highest ranking ever in the TIOBE index. Python's only serious drawbacks are (and thus leaving room for competition) its lack of performance and that most errors occur run-time.

For More Information   https://www.tiobe.com/tiobe-index/

Pomodoro Timer

 import tkinter as tk

from tkinter import messagebox

import time


# Constants

WORK_MIN = 25  # Work duration in minutes

SHORT_BREAK_MIN = 5  # Short break duration in minutes

LONG_BREAK_MIN = 15  # Long break duration in minutes

CYCLES = 4  # Number of work sessions before a long break


class PomodoroTimer:

    def __init__(self):

        self.root = tk.Tk()

        self.root.title("Pomodoro Timer")

        self.timer_running = False

        self.current_cycle = 0

        self.time_left = 0


        # UI Setup

        self.label = tk.Label(self.root, text="Pomodoro Timer", font=("Arial", 20))

        self.label.pack(pady=10)


        self.time_label = tk.Label(self.root, text="00:00", font=("Arial", 40))

        self.time_label.pack(pady=10)


        self.start_button = tk.Button(self.root, text="Start", font=("Arial", 15), command=self.start_timer)

        self.start_button.pack(side="left", padx=10)


        self.reset_button = tk.Button(self.root, text="Reset", font=("Arial", 15), command=self.reset_timer)

        self.reset_button.pack(side="right", padx=10)


    def start_timer(self):

        if not self.timer_running:

            self.current_cycle += 1

            if self.current_cycle % (CYCLES + 1) == 0:

                self.time_left = LONG_BREAK_MIN * 60

                self.label.config(text="Long Break", fg="blue")

            elif self.current_cycle % 2 == 0:

                self.time_left = SHORT_BREAK_MIN * 60

                self.label.config(text="Short Break", fg="green")

            else:

                self.time_left = WORK_MIN * 60

                self.label.config(text="Work", fg="red")


            self.timer_running = True

            self.countdown()


    def countdown(self):

        if self.time_left > 0:

            mins, secs = divmod(self.time_left, 60)

            self.time_label.config(text=f"{mins:02}:{secs:02}")

            self.time_left -= 1

            self.root.after(1000, self.countdown)

        else:

            self.timer_running = False

            self.time_label.config(text="00:00")

            if self.current_cycle % 2 != 0:

                messagebox.showinfo("Time's up!", "Time for a break!")

            else:

                messagebox.showinfo("Time's up!", "Time to work!")


    def reset_timer(self):

        self.timer_running = False

        self.current_cycle = 0

        self.time_left = 0

        self.label.config(text="Pomodoro Timer", fg="black")

        self.time_label.config(text="00:00")


    def run(self):

        self.root.mainloop()


# Run the Pomodoro Timer

if __name__ == "__main__":

    PomodoroTimer().run()


News Aggregator


  • Visit NewsAPI and sign up for a free API key.
  • Replace your_newsapi_key in the code with your actual API key.

  •  import requests

    API_KEY = "your_newsapi_key"  # Replace with your NewsAPI key

    BASE_URL = "https://newsapi.org/v2/"


    def fetch_top_headlines(country="us", category="general", page_size=5):

        """

        Fetch top news headlines from NewsAPI.

        Args:

            country (str): Country code for news (default is 'us').

            category (str): Category of news (default is 'general').

            page_size (int): Number of headlines to fetch (default is 5).

        Returns:

            list: A list of dictionaries containing news headlines and details.

        """

        url = f"{BASE_URL}top-headlines"

        params = {

            "apiKey": API_KEY,

            "country": country,

            "category": category,

            "pageSize": page_size,

        }

        try:

            response = requests.get(url, params=params)

            response.raise_for_status()

            data = response.json()

            return data.get("articles", [])

        except requests.exceptions.RequestException as e:

            print(f"Error fetching news: {e}")

            return []


    def display_headlines(articles):

        """

        Display news headlines in a user-friendly format.


        Args:

            articles (list): List of news articles.

        """

        if not articles:

            print("No news articles found.")

            return

        print("\n--- Latest News Headlines ---")

        for idx, article in enumerate(articles, 1):

            print(f"\n{idx}. {article['title']}")

            print(f"   Source: {article['source']['name']}")

            print(f"   URL: {article['url']}")


    def main():

        print("Welcome to the News Aggregator!")

        country = input("Enter the country code for news (e.g., 'us' for USA, 'in' for India): ").strip()

        category = input("Enter the category of news (e.g., 'business', 'entertainment', 'sports'): ").strip()

        num_articles = input("How many articles would you like to fetch? (default is 5): ").strip()


        # Default values if input is empty

        country = country if country else "us"

        category = category if category else "general"

        num_articles = int(num_articles) if num_articles.isdigit() else 5


        print("\nFetching top headlines...")

        articles = fetch_top_headlines(country=country, category=category, page_size=num_articles)


        display_headlines(articles)


    if __name__ == "__main__":

        main()


    Stock Price Tracker

     import yfinance as yf

    import matplotlib.pyplot as plt

    import pandas as pd


    def get_stock_data(ticker, period='1mo', interval='1d'):

        """

        Fetch stock data for a given ticker.


        Args:

            ticker (str): The stock ticker symbol.

            period (str): The time period for historical data (e.g., '1mo', '1y').

            interval (str): The interval for the data (e.g., '1d', '1h').


        Returns:

            pandas.DataFrame: Historical stock data.

        """

        try:

            stock = yf.Ticker(ticker)

            data = stock.history(period=period, interval=interval)

            return data

        except Exception as e:

            print(f"Error fetching data: {e}")

            return None


    def plot_stock_data(data, ticker):

        """

        Plot stock closing price data.


        Args:

            data (pandas.DataFrame): Historical stock data.

            ticker (str): The stock ticker symbol.

        """

        if data is not None and not data.empty:

            plt.figure(figsize=(10, 6))

            plt.plot(data.index, data['Close'], label=f'{ticker} Closing Price')

            plt.title(f"{ticker} Stock Price")

            plt.xlabel("Date")

            plt.ylabel("Closing Price")

            plt.legend()

            plt.grid()

            plt.show()

        else:

            print("No data available to plot.")


    def main():

        print("Welcome to the Stock Price Tracker!")

        ticker = input("Enter the stock ticker symbol (e.g., AAPL, TSLA, GOOGL): ").upper()

        period = input("Enter the time period (default is '1mo', e.g., '1d', '1y'): ") or '1mo'

        interval = input("Enter the data interval (default is '1d', e.g., '1h', '1wk'): ") or '1d'


        print("\nFetching stock data...")

        data = get_stock_data(ticker, period, interval)

        

        if data is not None and not data.empty:

            print("\nStock data fetched successfully!")

            print(data.tail())  # Display the last 5 rows of data

            plot_stock_data(data, ticker)

        else:

            print("Failed to fetch stock data. Please check the ticker symbol or try again.")


    if __name__ == "__main__":

        main()