Category: Python

  • Universal Age & Birth Date Calculator Python Script

    This script calculates an age in years, months, and days from a given date of birth or determines an approximate birth date based on an exact age input.

    The script utilizes the python-dateutil library, which extends Python’s standard datetime module by offering the relativedelta class for sophisticated date arithmetic; install it using pip3 install python-dateutil if it’s not already available.

    Click to view script…
    #!/usr/bin/env python3
    from datetime import datetime
    try:
        from dateutil.relativedelta import relativedelta
    except ImportError:
        print("This script requires the 'python-dateutil' module. Install it via 'pip3 install python-dateutil'")
        exit(1)
    
    def calculate_age(birth_date, current_date):
        """Calculate the difference between two dates as (years, months, days) using relativedelta."""
        delta = relativedelta(current_date, birth_date)
        return delta.years, delta.months, delta.days
    
    def main():
        print("Select an option:")
        print("1. Calculate an age from a date of birth")
        print("2. Calculate a birth date from an exact age")
        choice = input("Enter 1 or 2: ").strip()
        
        today = datetime.today()
        
        if choice == "1":
            dob_str = input("Enter a date of birth (YYYY-MM-DD): ").strip()
            try:
                birth_date = datetime.strptime(dob_str, "%Y-%m-%d")
            except ValueError:
                print("Invalid date format. Please use YYYY-MM-DD.")
                exit(1)
            
            years, months, days = calculate_age(birth_date, today)
            print(f"Calculated age: {years} years, {months} months, and {days} days.")
        
        elif choice == "2":
            print("Enter an exact age as three numbers separated by spaces.")
            print("For example, if the age is 25 years, 4 months, and 15 days, type: 25 4 15")
            age_input = input("Exact age (years months days): ").strip()
            parts = age_input.split()
            if len(parts) != 3:
                print("Invalid input. Please enter three integers separated by spaces.")
                exit(1)
            try:
                years = int(parts[0])
                months = int(parts[1])
                days = int(parts[2])
            except ValueError:
                print("Invalid input. Please ensure you enter numbers for years, months, and days.")
                exit(1)
            
            birth_date = today - relativedelta(years=years, months=months, days=days)
            print("Calculated birth date is approximately:", birth_date.strftime("%Y-%m-%d"))
        
        else:
            print("Invalid option selected.")
    
    if __name__ == '__main__':
        main()
  • Unique Entry Filter Python Script

    This script prompts the user to enter a comma-separated list of strings, then processes the input by trimming whitespace and converting entries to lowercase for case-insensitive duplicate checking. It finally outputs a comma-separated list of unique entries, preserving the order of their first appearance.

    Click to view script…
    #!/usr/bin/env python3
    
    def remove_duplicates(input_string):
        # Split the input string by commas and remove any extra spaces
        items = [item.strip() for item in input_string.split(',')]
        unique_items = []
        seen = set()
    
        for item in items:
            # Convert to lowercase for case-insensitive comparison
            if item.lower() not in seen:
                seen.add(item.lower())
                unique_items.append(item)
        return unique_items
    
    if __name__ == '__main__':
        user_input = input("Enter a comma-separated list of strings: ")
        unique = remove_duplicates(user_input)
        print("Unique entries:", ", ".join(unique))
  • AES File Encryption & Decryption Utility Python Script

    A Python utility that allows users to securely encrypt or decrypt files using AES with a choice between 128‑bit and 256‑bit keys. It lists files from the current directory, prompts for password confirmation during encryption, and handles decryption seamlessly by deriving keys with PBKDF2 and using CBC mode.

    This script relies on the PyCryptodome library to handle AES encryption and decryption operations. Be sure to install it via pip install pycryptodome before running the script.

    Click to view script…
    #!/usr/bin/env python3
    import os
    import sys
    import getpass
    from Crypto.Cipher import AES
    from Crypto.Random import get_random_bytes
    from Crypto.Protocol.KDF import PBKDF2
    from Crypto.Util.Padding import pad, unpad
    
    HEADER_MAGIC = b"ENCR"  # 4 bytes header to identify our encrypted files
    SALT_SIZE = 16          # Salt size in bytes
    IV_SIZE = 16            # AES block size
    PBKDF2_ITERATIONS = 100000
    
    def list_files():
        files = [f for f in os.listdir('.') if os.path.isfile(f)]
        if not files:
            print("No files found in the current directory.")
            sys.exit(1)
        print("Files in the current directory:")
        for i, f in enumerate(files, start=1):
            print(f"  {i}. {f}")
        return files
    
    def choose_file(files):
        try:
            choice = int(input("Select a file number: "))
            if choice < 1 or choice > len(files):
                raise ValueError
        except ValueError:
            print("Invalid selection.")
            sys.exit(1)
        return files[choice - 1]
    
    def get_password(confirm=False):
        pwd = getpass.getpass("Enter password: ")
        if confirm:
            pwd_confirm = getpass.getpass("Confirm password: ")
            if pwd != pwd_confirm:
                print("Passwords do not match.")
                sys.exit(1)
        return pwd.encode()  # work with bytes
    
    def encrypt_file(filepath):
        print("\n--- Encryption ---")
        # Choose key size
        key_size_choice = input("Choose key size (enter 128 or 256): ").strip()
        if key_size_choice not in ("128", "256"):
            print("Invalid key size selection.")
            sys.exit(1)
        key_len = 16 if key_size_choice == "128" else 32
    
        password = get_password(confirm=True)
    
        # Generate a random salt and IV
        salt = get_random_bytes(SALT_SIZE)
        iv = get_random_bytes(IV_SIZE)
    
        # Derive the AES key from the password and salt
        key = PBKDF2(password, salt, dkLen=key_len, count=PBKDF2_ITERATIONS)
    
        # Read file data
        try:
            with open(filepath, "rb") as f:
                data = f.read()
        except IOError as e:
            print(f"Error reading file: {e}")
            sys.exit(1)
    
        # Pad and encrypt the data using CBC mode
        cipher = AES.new(key, AES.MODE_CBC, iv)
        ciphertext = cipher.encrypt(pad(data, AES.block_size))
    
        # Create an output file format:
        # [4 bytes header][1 byte key length indicator][16 bytes salt][16 bytes IV][ciphertext]
        # We store key length as one byte: 16 (for 128-bit) or 32 (for 256-bit)
        header = HEADER_MAGIC + bytes([key_len]) + salt + iv
        out_data = header + ciphertext
    
        # Determine output file name
        out_filepath = filepath + ".enc"
        try:
            with open(out_filepath, "wb") as f:
                f.write(out_data)
        except IOError as e:
            print(f"Error writing encrypted file: {e}")
            sys.exit(1)
    
        print(f"Encryption successful. Encrypted file: {out_filepath}")
    
    def decrypt_file(filepath):
        print("\n--- Decryption ---")
        # Read the encrypted file and parse header information
        try:
            with open(filepath, "rb") as f:
                file_data = f.read()
        except IOError as e:
            print(f"Error reading file: {e}")
            sys.exit(1)
    
        # Verify header length
        header_length = len(HEADER_MAGIC) + 1 + SALT_SIZE + IV_SIZE
        if len(file_data) < header_length:
            print("File is too short to be a valid encrypted file.")
            sys.exit(1)
    
        header = file_data[:len(HEADER_MAGIC)]
        if header != HEADER_MAGIC:
            print("Invalid file format (missing header).")
            sys.exit(1)
    
        key_len = file_data[len(HEADER_MAGIC)]
        if key_len not in (16, 32):
            print("Invalid key length in file header.")
            sys.exit(1)
    
        salt = file_data[len(HEADER_MAGIC)+1 : len(HEADER_MAGIC)+1+SALT_SIZE]
        iv_start = len(HEADER_MAGIC)+1+SALT_SIZE
        iv = file_data[iv_start : iv_start+IV_SIZE]
        ciphertext = file_data[iv_start+IV_SIZE:]
    
        password = get_password(confirm=False)
        key = PBKDF2(password, salt, dkLen=key_len, count=PBKDF2_ITERATIONS)
    
        # Decrypt and unpad the data
        cipher = AES.new(key, AES.MODE_CBC, iv)
        try:
            plaintext_padded = cipher.decrypt(ciphertext)
            plaintext = unpad(plaintext_padded, AES.block_size)
        except (ValueError, KeyError):
            print("Decryption failed. Incorrect password or corrupted file.")
            sys.exit(1)
    
        # Determine output file name
        if filepath.endswith(".enc"):
            out_filepath = filepath[:-4]  # remove the .enc extension
        else:
            out_filepath = filepath + ".dec"
    
        try:
            with open(out_filepath, "wb") as f:
                f.write(plaintext)
        except IOError as e:
            print(f"Error writing decrypted file: {e}")
            sys.exit(1)
    
        print(f"Decryption successful. Decrypted file: {out_filepath}")
    
    def main():
        print("AES Encryption/Decryption Utility")
        mode = input("Do you want to (E)ncrypt or (D)ecrypt? ").strip().lower()
        if mode not in ("e", "d"):
            print("Invalid mode selection.")
            sys.exit(1)
    
        files = list_files()
        selected_file = choose_file(files)
    
        if mode == "e":
            encrypt_file(selected_file)
        else:
            decrypt_file(selected_file)
    
    if __name__ == "__main__":
        main()
    
  • QR Code Generator Python Script

    This Python script uses the qrcode library to convert user-provided text or URLs into a QR code image, which is saved as a PNG file. It offers a simple way to quickly generate and share QR codes directly from your terminal.

    Click to view script…
    #!/usr/bin/env python3
    import qrcode
    
    def generate_qr_code(data, filename="qr_code.png"):
        """
        Generates a QR code from the provided data and saves it to a file.
    
        Parameters:
            data (str): The text or URL to encode.
            filename (str): The name of the file to save the QR code image.
        
        Returns:
            str: The filename where the QR code is saved.
        """
        # Create a QRCode object with desired settings.
        qr = qrcode.QRCode(
            version=1,  # 1 means 21x21 matrix; increase for more data.
            error_correction=qrcode.constants.ERROR_CORRECT_H,  # High error correction.
            box_size=10,  # Size of each box in pixels.
            border=4,  # Border size in boxes.
        )
        
        # Add data to the QR code.
        qr.add_data(data)
        qr.make(fit=True)
        
        # Create an image from the QR code instance.
        img = qr.make_image(fill_color="black", back_color="white")
        img.save(filename)
        return filename
    
    def main():
        print("=== QR Code Generator ===\n")
        data = input("Enter the text or URL you want to encode in the QR code: ").strip()
        if not data:
            print("No data provided. Exiting.")
            return
    
        filename = generate_qr_code(data)
        print(f"\nQR code generated and saved as '{filename}'.")
    
    if __name__ == "__main__":
        main()
  • True or False Trivia Challenge Python Script

    This interactive quiz game lets you explore fun categories by answering unique True/False questions. With each question, you’ll receive immediate feedback and an insightful explanation to expand your knowledge.

    Click to view script…
    #!/usr/bin/env python3
    import random
    
    def main():
        categories = {
            "1": {
                "name": "Animal Trivia",
                "questions": [
                    {
                        "question": "Elephants are the only animals that can't jump.",
                        "answer": True,
                        "description": "True! Due to their massive weight and unique limb structure, elephants are physically incapable of jumping."
                    },
                    {
                        "question": "Bats are blind.",
                        "answer": False,
                        "description": "False! While bats use echolocation, they also have functional eyes and can see."
                    },
                    {
                        "question": "A group of flamingos is called a 'flamboyance'.",
                        "answer": True,
                        "description": "True! The collective noun for flamingos is indeed 'flamboyance', which suits their vibrant appearance."
                    },
                    {
                        "question": "An octopus has three hearts.",
                        "answer": True,
                        "description": "True! Octopuses have two branchial hearts and one systemic heart."
                    },
                    {
                        "question": "Goldfish have a memory span of just three seconds.",
                        "answer": False,
                        "description": "False! Goldfish can actually remember things for months."
                    }
                ]
            },
            "2": {
                "name": "Space Facts",
                "questions": [
                    {
                        "question": "A day on Venus is longer than its year.",
                        "answer": True,
                        "description": "True! Venus rotates very slowly, making its day longer than the time it takes to orbit the Sun."
                    },
                    {
                        "question": "There is no sound in space.",
                        "answer": True,
                        "description": "True! Space is a vacuum, so sound cannot travel."
                    },
                    {
                        "question": "Mars has the tallest volcano in the solar system, Olympus Mons.",
                        "answer": True,
                        "description": "True! Olympus Mons on Mars stands about 22 kilometers high, making it the tallest volcano known."
                    },
                    {
                        "question": "Saturn is the only planet with rings.",
                        "answer": False,
                        "description": "False! While Saturn’s rings are the most prominent, Jupiter, Uranus, and Neptune also have ring systems."
                    },
                    {
                        "question": "The footprints on the Moon will disappear over time due to wind erosion.",
                        "answer": False,
                        "description": "False! The Moon has no atmosphere or wind, so the footprints will likely remain for millions of years."
                    }
                ]
            },
            "3": {
                "name": "History Myths",
                "questions": [
                    {
                        "question": "Napoleon Bonaparte was extremely short.",
                        "answer": False,
                        "description": "False! Napoleon was of average height for his era; the myth of his short stature comes from a misunderstanding of French measurements."
                    },
                    {
                        "question": "The Great Wall of China is visible from space.",
                        "answer": False,
                        "description": "False! The Great Wall is very narrow and follows the natural contours of the land, making it nearly impossible to see from space with the naked eye."
                    },
                    {
                        "question": "Vikings wore horned helmets.",
                        "answer": False,
                        "description": "False! There is no historical evidence that Vikings ever wore horned helmets; this image was popularized by 19th-century artists."
                    },
                    {
                        "question": "The French Revolution began in 1789.",
                        "answer": True,
                        "description": "True! The French Revolution, which reshaped France and influenced modern democracies, began in 1789."
                    },
                    {
                        "question": "Christopher Columbus made his first voyage to the Americas in 1492.",
                        "answer": True,
                        "description": "True! In 1492, Columbus set sail, marking the beginning of European exploration of the Americas."
                    }
                ]
            }
        }
    
        print("Welcome to the True/False Quiz Game!")
        
        while True:
            print("\nChoose a category for your quiz:")
            for key, cat in categories.items():
                print(f"{key}. {cat['name']}")
            print("Q. Quit")
            
            choice = input("Enter your choice: ").strip().lower()
            if choice == 'q':
                print("Thanks for playing! Goodbye!")
                break
            
            if choice not in categories:
                print("Invalid choice. Please try again.")
                continue
            
            selected_cat = categories[choice]
            print(f"\nYou selected: {selected_cat['name']}")
            # Create a local copy of the questions list so each question is shown only once.
            available_questions = selected_cat["questions"].copy()
            
            while available_questions:
                question = random.choice(available_questions)
                available_questions.remove(question)
                
                print("\n" + question["question"])
                user_answer = input("Type T for True or F for False: ").strip().lower()
                
                if user_answer not in ["t", "f"]:
                    print("Invalid input. Please type 'T' or 'F'.")
                    continue
                
                user_bool = True if user_answer == "t" else False
                
                if user_bool == question["answer"]:
                    print("Correct!")
                else:
                    print("Incorrect!")
                
                print("Explanation:", question["description"])
                
                # Check if there are more questions available.
                if available_questions:
                    another = input("\nWould you like another question from this category? (y/n): ").strip().lower()
                    if another != "y":
                        break
                else:
                    print("\nNo more questions left in this category.")
                    
    if __name__ == "__main__":
        main()
  • Historical News Fun Facts Python Script

    This Python script provides an interactive and engaging way to learn about major historical news events. Users can choose from a variety of categories and receive a random, interesting fact from each, making history both fun and informative.

    Click to view script…
    #!/usr/bin/env python3
    import random
    
    def main():
        categories = {
            "1": {
                "name": "Wars & Conflicts",
                "facts": [
                    "World War II (1939-1945) saw the largest mobilization of military forces in history.",
                    "The American Civil War (1861-1865) led to the abolition of slavery in the United States.",
                    "World War I (1914-1918) introduced modern warfare techniques like tanks and chemical warfare.",
                    "The Vietnam War sparked significant anti-war protests and shaped global politics for decades.",
                    "The Korean War (1950-1953) ended in an armistice, leaving the Korean Peninsula divided.",
                    "The Gulf War (1990-1991) was one of the first conflicts broadcast live on television.",
                    "The Napoleonic Wars reshaped Europe in the early 19th century.",
                    "The Crimean War (1853-1856) saw the first use of the telegraph for military communication.",
                    "The Thirty Years' War (1618-1648) was one of the longest and most destructive conflicts in Europe.",
                    "The Falklands War (1982) highlighted the lingering effects of colonial disputes."
                ]
            },
            "2": {
                "name": "Political Milestones",
                "facts": [
                    "The fall of the Berlin Wall in 1989 symbolized the end of the Cold War.",
                    "Nelson Mandela's release in 1990 marked a significant step toward ending apartheid in South Africa.",
                    "The Declaration of Independence in 1776 laid the foundation for the United States.",
                    "The French Revolution (1789-1799) radically transformed France’s political and social structure.",
                    "India gained independence from British colonial rule in 1947.",
                    "The establishment of the United Nations in 1945 aimed to promote peace and cooperation globally.",
                    "The suffragette movement secured voting rights for women in many countries during the early 20th century.",
                    "The end of the Cold War in 1991 reshaped global political alliances.",
                    "The formation of the European Union helped unify post-war Europe.",
                    "The Arab Spring in the early 2010s spurred political change across several Middle Eastern countries."
                ]
            },
            "3": {
                "name": "Tech & Science Breakthroughs",
                "facts": [
                    "The Apollo 11 moon landing in 1969 was watched live by millions around the globe.",
                    "The invention of the internet revolutionized communication and information sharing.",
                    "The Human Genome Project, completed in 2003, mapped the entire human genetic code.",
                    "The launch of the Hubble Space Telescope in 1990 expanded our view of the universe.",
                    "The discovery of penicillin in 1928 marked the beginning of modern antibiotics.",
                    "The advent of smartphones has transformed everyday communication and connectivity.",
                    "ENIAC, one of the first computers built in 1945, paved the way for the computer age.",
                    "Quantum computing promises to tackle problems beyond the capabilities of classical computers.",
                    "The discovery of the Higgs boson in 2012 confirmed the mechanism that gives particles mass.",
                    "CRISPR technology is revolutionizing genetics through precise gene editing."
                ]
            },
            "4": {
                "name": "Natural Disasters",
                "facts": [
                    "The 2004 Indian Ocean tsunami is one of the deadliest natural disasters in modern history.",
                    "The eruption of Mount Vesuvius in AD 79 famously buried the Roman cities of Pompeii and Herculaneum.",
                    "The 1906 San Francisco earthquake led to massive destruction and a major rebuild of the city.",
                    "Hurricane Katrina in 2005 devastated the Gulf Coast region of the United States.",
                    "The Great Galveston Hurricane of 1900 remains the deadliest natural disaster in U.S. history.",
                    "The 2011 Tōhoku earthquake and tsunami in Japan triggered a nuclear crisis at Fukushima.",
                    "The Dust Bowl of the 1930s severely impacted agriculture and displaced thousands in the American Midwest.",
                    "The 1980 eruption of Mount St. Helens was one of the most significant volcanic events in U.S. history.",
                    "The Lisbon earthquake of 1755 had far-reaching effects on European philosophy and society.",
                    "The Bhola cyclone of 1970 was one of the most catastrophic tropical cyclones ever recorded."
                ]
            },
            "5": {
                "name": "Cultural & Entertainment Events",
                "facts": [
                    "The Beatles’ appearance on The Ed Sullivan Show in 1964 kick-started Beatlemania in the U.S.",
                    "Woodstock in 1969 became an iconic symbol of the counterculture movement.",
                    "The launch of MTV in 1981 revolutionized the music industry and pop culture.",
                    "Blockbuster movies emerged in the 1970s, forever changing the film industry.",
                    "The first Academy Awards in 1929 established a global benchmark for cinematic achievement.",
                    "Reality TV's rise in the early 2000s reshaped modern television programming.",
                    "The global popularity of video games has transformed entertainment and technology industries.",
                    "Social media platforms in the 21st century have redefined celebrity culture and public interaction.",
                    "Streaming services have dramatically changed how audiences consume films and television shows.",
                    "Internet memes have become a defining aspect of digital culture in recent years."
                ]
            }
        }
        
        while True:
            print("\n=== Fun Fact Utility: Biggest News Events in History ===")
            print("Choose a category for a fun fact:")
            for key, value in categories.items():
                print(f"{key}. {value['name']}")
            print("Q. Quit")
            
            choice = input("Enter your choice: ").strip().lower()
            if choice == 'q':
                print("Goodbye!")
                break
            elif choice in categories:
                fact = random.choice(categories[choice]["facts"])
                print(f"\nFun Fact from {categories[choice]['name']}:")
                print(fact)
            else:
                print("Invalid choice. Please select a valid category.")
    
    if __name__ == "__main__":
        main()
  • URL Shortener Python Script

    This script is a straightforward and user-friendly URL shortener that leverages the TinyURL API to convert long URLs into compact, shareable links. It prompts the user for a URL, processes it through the API, and then displays both the original and shortened URLs for easy reference.

    This script requires the requests library to handle HTTP requests to the TinyURL API. Make sure to install it with pip install requests before running the script.

    Click to view script…
    #!/usr/bin/env python3
    import requests
    
    def shorten_url(url):
        """
        Shortens the given URL using the TinyURL API.
        
        Parameters:
            url (str): The original URL.
        
        Returns:
            str: The shortened URL or None if something went wrong.
        """
        api_url = 'https://tinyurl.com/api-create.php'
        params = {'url': url}
        try:
            response = requests.get(api_url, params=params)
            if response.status_code == 200:
                return response.text.strip()
            else:
                print(f"Error: Unable to shorten URL. Status code: {response.status_code}")
                return None
        except Exception as e:
            print("Error during request:", e)
            return None
    
    def main():
        print("=== Welcome to the Python URL Shortener ===\n")
        
        # Get URL from user
        original_url = input("Enter the URL you want to shorten: ").strip()
        if not original_url:
            print("No URL provided. Exiting.")
            return
    
        # Get the shortened URL
        shortened_url = shorten_url(original_url)
        if shortened_url:
            # Display the original and shortened URLs
            print("\nHere are your URLs:")
            print("-" * 40)
            print("Original URL:  ", original_url)
            print("Shortened URL: ", shortened_url)
            print("-" * 40)
        else:
            print("Failed to shorten the URL.")
    
    if __name__ == "__main__":
        main()

  • Typing Speed Test Python Script

    This Python script challenges your typing skills by randomly selecting one of ten unique sentences and measuring your typing speed in words per minute.

    Click to view script…
    #!/usr/bin/env python3
    import time
    import random
    
    def typing_speed_test():
        # List of 10 extremely unique sentences for the user to type
        sentences = [
            "The iridescent butterfly fluttered past the ancient clock tower as whispers of the past filled the air.",
            "Under a kaleidoscope sky, the lonely wanderer discovered a secret garden blooming with surreal neon flowers.",
            "Amidst the cosmic silence, a forgotten melody echoed through the labyrinth of interstellar dreams.",
            "In the midst of the bustling city, a solitary violinist played tunes that painted the sunrise in shades of hope.",
            "A cascade of luminous raindrops transformed the mundane street into a magical canvas of vibrant reflections.",
            "The mischievous fox leaped over a neon moon as the forest whispered untold legends in the darkness.",
            "Beneath the ancient cedar, time melted like caramel under the gentle touch of twilight.",
            "A carnival of shadows danced along the deserted boulevard, each step echoing forgotten tales.",
            "In a realm where gravity lost its grip, dreams soared like vivid kites against a starlit backdrop.",
            "The enigmatic street artist splashed abstract dreams onto concrete walls, creating a symphony of colors under midnight skies."
        ]
        
        # Randomly choose one sentence from the list
        sentence = random.choice(sentences)
        
        # Display instructions and the chosen sentence
        print("Typing Speed Tester")
        print("-------------------")
        print("Type the following sentence as quickly and accurately as you can:\n")
        print(sentence + "\n")
        input("Press Enter when you're ready to start...")
    
        print("\nStart typing below:\n")
        
        # Start the timer and capture the user's input
        start_time = time.time()
        typed_text = input()
        end_time = time.time()
        
        # Calculate elapsed time
        elapsed_time = end_time - start_time
    
        # Count the number of words in the sentence
        word_count = len(sentence.split())
        
        # Calculate words per minute (WPM)
        wpm = (word_count / elapsed_time) * 60
    
        print("\nResults:")
        print("Time taken: {:.2f} seconds".format(elapsed_time))
        print("Your typing speed is: {:.2f} words per minute (WPM)".format(wpm))
        
    if __name__ == "__main__":
        typing_speed_test()

  • Live Stock Price Tracker Python Script

    This Python script fetches live stock prices for a specified ticker using the yfinance library and logs the data with a timestamp into a CSV file for further analysis. It provides an easy way to monitor and record real-time market price movements.

    If you haven’t installed yfinance yet, you can easily add it by running the following command in your terminal:

    pip install yfinance
    Click to view script…
    #!/usr/bin/env python3
    import yfinance as yf
    import csv
    import os
    from datetime import datetime
    
    def fetch_stock_price(ticker_symbol):
        """
        Fetches the current stock price for the given ticker symbol using yfinance.
        It first tries to get the 'regularMarketPrice' from the ticker info.
        If that fails, it falls back to using the latest close price from recent historical data.
        """
        ticker = yf.Ticker(ticker_symbol)
        try:
            # Attempt to get the live price from the info dictionary
            info = ticker.info
            price = info.get("regularMarketPrice", None)
            if price is None:
                # Fallback: get the most recent closing price from historical data
                data = ticker.history(period="1d", interval="1m")
                price = data["Close"].iloc[-1]
        except Exception as e:
            print(f"Error fetching data for {ticker_symbol}: {e}")
            return None
        return price
    
    def store_stock_price(ticker_symbol, price, filename="stock_prices.csv"):
        """
        Stores the fetched stock price along with a timestamp and the ticker symbol into a CSV file.
        If the file does not exist, it creates one with appropriate headers.
        """
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        header = ["timestamp", "ticker", "price"]
        file_exists = os.path.isfile(filename)
        
        with open(filename, mode="a", newline="") as file:
            writer = csv.writer(file)
            if not file_exists:
                writer.writerow(header)
            writer.writerow([now, ticker_symbol, price])
        
        print(f"Stored price for {ticker_symbol} at {now} in {filename}.")
    
    def main():
        print("Stock Price Tracker")
        print("-------------------")
        print("Fetches live stock prices and stores them for analysis.\n")
        
        ticker_symbol = input("Enter the stock ticker (e.g., AAPL): ").strip().upper()
        if not ticker_symbol:
            print("No ticker entered. Exiting.")
            return
        
        price = fetch_stock_price(ticker_symbol)
        if price is not None:
            print(f"Current price of {ticker_symbol}: ${price:.2f}")
            store_stock_price(ticker_symbol, price)
        else:
            print("Failed to fetch stock price.")
    
    if __name__ == "__main__":
        main()
  • Universal Temperature Converter Python Script

    This script converts temperatures between Celsius, Fahrenheit, and Kelvin using a simple, menu-driven interface. It allows users to easily input a temperature value and select a conversion option to quickly view the result.

    Click to view script…
    #!/usr/bin/env python3
    
    def celsius_to_fahrenheit(c):
        return (c * 9/5) + 32
    
    def celsius_to_kelvin(c):
        return c + 273.15
    
    def fahrenheit_to_celsius(f):
        return (f - 32) * 5/9
    
    def fahrenheit_to_kelvin(f):
        return (f - 32) * 5/9 + 273.15
    
    def kelvin_to_celsius(k):
        return k - 273.15
    
    def kelvin_to_fahrenheit(k):
        return (k - 273.15) * 9/5 + 32
    
    def main():
        print("Temperature Converter")
        print("---------------------")
        print("Converts temperatures between Celsius, Fahrenheit, and Kelvin.\n")
        
        while True:
            print("Conversion options:")
            print("1. Celsius to Fahrenheit")
            print("2. Celsius to Kelvin")
            print("3. Fahrenheit to Celsius")
            print("4. Fahrenheit to Kelvin")
            print("5. Kelvin to Celsius")
            print("6. Kelvin to Fahrenheit")
            choice = input("Enter your choice (1-6) or 'q' to quit: ")
            
            if choice.lower() == 'q':
                print("Goodbye!")
                break
            
            try:
                choice = int(choice)
            except ValueError:
                print("Invalid input. Please enter a number between 1 and 6, or 'q' to quit.\n")
                continue
            
            if choice < 1 or choice > 6:
                print("Invalid choice. Please choose a valid conversion option.\n")
                continue
            
            temp_input = input("Enter the temperature value: ")
            try:
                temp = float(temp_input)
            except ValueError:
                print("Invalid temperature value. Please enter a numeric value.\n")
                continue
            
            if choice == 1:
                result = celsius_to_fahrenheit(temp)
                print(f"{temp}°C is equal to {result:.2f}°F\n")
            elif choice == 2:
                result = celsius_to_kelvin(temp)
                print(f"{temp}°C is equal to {result:.2f} K\n")
            elif choice == 3:
                result = fahrenheit_to_celsius(temp)
                print(f"{temp}°F is equal to {result:.2f}°C\n")
            elif choice == 4:
                result = fahrenheit_to_kelvin(temp)
                print(f"{temp}°F is equal to {result:.2f} K\n")
            elif choice == 5:
                result = kelvin_to_celsius(temp)
                print(f"{temp} K is equal to {result:.2f}°C\n")
            elif choice == 6:
                result = kelvin_to_fahrenheit(temp)
                print(f"{temp} K is equal to {result:.2f}°F\n")
                
    if __name__ == "__main__":
        main()