Category: Python

  • iTunes Top Songs & Albums Purchases Python Script

    This Python script fetches and displays the current top songs or albums based on purchases from the iTunes Store. Users can select a category and the number of entries to view, with rankings clearly labeled to reflect purchase trends as of the check date.

    Click to view script…
    #!/usr/bin/env python3
    # iTunes Top Purchases Scraper
    # Purpose: Fetches and displays the current top songs or albums based on purchases from the iTunes Store.
    # Note: This script shows purchase-based rankings, not streaming data.
    
    import requests
    from datetime import datetime
    
    # Define categories with their display names and RSS feed paths
    categories = {
        1: {'name': 'Top Songs (Purchases)', 'path': 'topsongs'},
        2: {'name': 'Top Albums (Purchases)', 'path': 'topalbums'}
    }
    
    def main():
        """Main function to run the iTunes Top Purchases Scraper."""
        # Inform the user that the data reflects purchases, not streaming
        print("Welcome! This script shows top songs or albums based on purchases from the iTunes Store (not streaming data).")
        
        # Display category options
        print("\nSelect a category:")
        for key, value in categories.items():
            print(f"{key}. {value['name']}")
        
        # Get and validate category choice
        choice_input = input("Enter the number of your choice: ")
        try:
            choice = int(choice_input)
            if choice not in categories:
                raise ValueError
        except ValueError:
            print("Invalid choice. Please run the script again and enter 1 or 2.")
            return
        
        category = categories[choice]
        category_name = category['name']
        
        # Get and validate number of entries
        limit_input = input("Enter the number of entries to display (1-100, default 10): ")
        if limit_input.strip() == "":
            limit = 10
        else:
            try:
                limit = int(limit_input)
                if limit < 1 or limit > 100:
                    print("Limit must be between 1 and 100. Using default of 10.")
                    limit = 10
            except ValueError:
                print("Invalid input. Using default of 10.")
                limit = 10
        
        # Construct the RSS feed URL
        url = f"https://itunes.apple.com/us/rss/{category['path']}/limit={limit}/json"
        
        # Record the current date and time
        check_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Fetch data from the iTunes RSS feed
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            return
        
        # Extract entries from the JSON response
        feed = data.get('feed', {})
        entries = feed.get('entry', [])
        
        if not entries:
            print("No data available for this category.")
            return
        
        # Display the results
        print(f"\n{category_name} as of {check_date}")
        print(f"{'Rank':<5} {'Name':<50} {'Artist':<30}")
        print("-" * 85)
        
        for i, entry in enumerate(entries, start=1):
            name = entry.get('im:name', {}).get('label', 'N/A')
            artist = entry.get('im:artist', {}).get('label', 'N/A')
            print(f"{i:<5} {name:<50} {artist:<30}")
    
    if __name__ == '__main__':
        main()
  • iOS App Store Comparison Tool Python Script

    This Python script enables users to compare multiple iOS apps by inputting their names, retrieving details like ratings, versions, and descriptions from the iTunes Search API. It displays a side-by-side overview of each app’s name, short description, rating count, rating stars, current version, and the date the check was initiated.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Initialize a list to store app names
    app_names = []
    while True:
        app_name = input("Enter app name: ")
        app_names.append(app_name)
        another = input("Do you want to add another app? (y/n): ").lower()
        if another != 'y':
            break
    
    # Record the current date and time when the check is initiated
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Initialize a list to store app data
    apps_data = []
    
    # Query the iTunes Search API for each app
    for app_name in app_names:
        try:
            response = requests.get(
                "https://itunes.apple.com/search",
                params={"term": app_name, "country": "us", "media": "software"}
            )
            response.raise_for_status()  # Raise an exception for HTTP errors
            data = response.json()
    
            if data["resultCount"] > 0:
                # Take the first result as the most relevant app
                app = data["results"][0]
                
                # Create a short description from the first 20 words of the full description
                words = app["description"].split()
                short_description = " ".join(words[:20]) + "..." if len(words) > 20 else " ".join(words)
                
                # Get the rating stars, formatting to one decimal place if available
                rating_stars = app.get("averageUserRating", "N/A")
                if rating_stars != "N/A":
                    rating_stars = f"{rating_stars:.1f}"
                
                # Compile the app information
                app_info = {
                    "app_name": app["trackName"],
                    "short_description": short_description,
                    "rating_count": app.get("userRatingCount", 0),
                    "rating_stars": rating_stars,
                    "current_version": app.get("version", "N/A"),
                    "check_date": current_time
                }
            else:
                app_info = {
                    "app_name": app_name,
                    "error": "App not found"
                }
        except requests.exceptions.RequestException as e:
            app_info = {
                "app_name": app_name,
                "error": f"Error fetching data: {e}"
            }
        
        apps_data.append(app_info)
    
    # Display the information for all apps
    for app_info in apps_data:
        if "error" in app_info:
            print(f"App Name: {app_info['app_name']}")
            print(f"Error: {app_info['error']}")
        else:
            print(f"App Name: {app_info['app_name']}")
            print(f"Short Description: {app_info['short_description']}")
            print(f"Rating Count: {app_info['rating_count']}")
            print(f"Rating Stars: {app_info['rating_stars']}")
            print(f"Current Version: {app_info['current_version']}")
            print(f"Check Date: {app_info['check_date']}")
        print("-" * 40)
  • iOS App Store Rating Checker Python Script

    This Python script allows users to input an iOS app name and retrieves its overall rating and total number of ratings from the iTunes Search API. It also displays the current date and time when the data was checked, providing a simple way to monitor app performance on the App Store.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Get the app name from the user
    app_name = input("Enter the app name: ")
    
    # Base URL for the iTunes Search API
    base_url = "https://itunes.apple.com/search"
    
    # Parameters for the API request
    params = {
        "term": app_name,
        "country": "us",
        "media": "software"
    }
    
    try:
        # Send GET request to the API
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # Raise an exception for HTTP errors
    
        # Parse the JSON response
        data = response.json()
    
        # Check if any apps were found
        if data["resultCount"] > 0:
            # Extract the first app's data
            app = data["results"][0]
            rating = app.get("averageUserRating", "N/A")
            if rating != "N/A":
                rating = f"{rating:.1f}"  # Format rating to one decimal place
            count = app.get("userRatingCount", "N/A")
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
            # Print the results
            print(f"App Name: {app['trackName']}")
            print(f"Overall Rating: {rating}")
            print(f"Total Ratings: {count}")
            print(f"Date Checked: {current_time}")
        else:
            print("No apps found with that name.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
  • Sleep Pattern Analyzer Python Script

    A Python script to track your sleep patterns by logging bed and wake times, and rate your sleep quality. Get insights like average sleep hours, best sleep nights, and view sleep data for any specific date.

    Click to view script…
    import json
    import os
    from datetime import datetime, timedelta
    
    # Load existing entries from the JSON file
    if os.path.exists("sleep_log.json"):
        with open("sleep_log.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new sleep entry, (2) look up sleep statistics, or (3) view sleep data for a specific date? Enter 1, 2, or 3: ").strip()
    
    if action == "1":
        # Record a new sleep entry
        date_input = input("Enter the date (YYYY-MM-DD) or press enter for today: ").strip()
        if date_input == "":
            date = datetime.now().strftime("%Y-%m-%d")
        else:
            date = date_input  # Assuming correct input for simplicity
    
        bed_time = input("Enter bed time (HH:MM): ").strip()
        wake_time = input("Enter wake time (HH:MM): ").strip()
        
        while True:
            try:
                quality = int(input("Enter quality rating (1-5): "))
                if 1 <= quality <= 5:
                    break
                else:
                    print("Please enter a number between 1 and 5.")
            except ValueError:
                print("Invalid input. Please enter an integer.")
        
        # Calculate hours slept
        bed_dt = datetime.strptime(date + " " + bed_time, "%Y-%m-%d %H:%M")
        wake_dt = datetime.strptime(date + " " + wake_time, "%Y-%m-%d %H:%M")
        if wake_dt < bed_dt:
            wake_dt += timedelta(days=1)
        hours_slept = (wake_dt - bed_dt).total_seconds() / 3600
        
        new_entry = {
            "date": date,
            "bed_time": bed_time,
            "wake_time": wake_time,
            "hours_slept": hours_slept,
            "quality": quality
        }
        entries.append(new_entry)
        
        with open("sleep_log.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Sleep recorded: {hours_slept:.2f} hours with quality {quality}")
        
        if len(entries) > 1:
            prev_entry = entries[-2]
            diff = hours_slept - prev_entry["hours_slept"]
            if diff > 0:
                print(f"You slept {diff:.2f} hours more than the previous night.")
            elif diff < 0:
                print(f"You slept {-diff:.2f} hours less than the previous night.")
            else:
                print("You slept the same number of hours as the previous night.")
    
    elif action == "2":
        # Look up sleep statistics
        if not entries:
            print("No sleep entries found. Please record a sleep entry first.")
        else:
            # Calculate overall average sleep hours
            total_hours = sum(entry["hours_slept"] for entry in entries)
            avg_hours = total_hours / len(entries)
            print(f"Overall average sleep hours: {avg_hours:.2f} hours")
            
            # Average sleep hours in the last 7 days
            today = datetime.now()
            last_7_days = [entry for entry in entries if (today - datetime.strptime(entry["date"], "%Y-%m-%d")).days < 7]
            if last_7_days:
                avg_last_7 = sum(entry["hours_slept"] for entry in last_7_days) / len(last_7_days)
                print(f"Average sleep hours in the last 7 days: {avg_last_7:.2f} hours")
            else:
                print("No entries in the last 7 days.")
            
            # Best night's sleep (longest hours)
            best_hours_entry = max(entries, key=lambda x: x["hours_slept"])
            print(f"Best night's sleep: {best_hours_entry['hours_slept']:.2f} hours on {best_hours_entry['date']}")
            
            # Best quality sleep (highest rating)
            best_quality_entry = max(entries, key=lambda x: x["quality"])
            print(f"Best quality sleep: rating {best_quality_entry['quality']} on {best_quality_entry['date']}")
    
    elif action == "3":
        # View sleep data for a specific date
        if not entries:
            print("No sleep entries found. Please record a sleep entry first.")
        else:
            user_date = input("Enter the date to look up (YYYY-MM-DD): ").strip()
            matching_entries = [entry for entry in entries if entry['date'] == user_date]
            
            if matching_entries:
                print(f"\nSleep data for {user_date}:")
                for entry in matching_entries:
                    print(f"- Bed time: {entry['bed_time']}")
                    print(f"  Wake time: {entry['wake_time']}")
                    print(f"  Hours slept: {entry['hours_slept']:.2f}")
                    print(f"  Quality: {entry['quality']}")
            else:
                print(f"No sleep entries found for {user_date}.")
    
    else:
        print("Invalid choice. Please run the script again and enter 1, 2, or 3.")
  • Food Price Tracker Python Script

    A Python script for recording and analyzing food prices from different locations. Track your favorite dishes, find the cheapest spots, and get insights like average prices per location and the best deal overall.

    Click to view script…
    import json
    import os
    from datetime import datetime
    from statistics import mean
    
    # Load existing entries from the JSON file
    if os.path.exists("food_prices.json"):
        with open("food_prices.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new food price or (2) look up past food prices? Enter 1 or 2: ").strip()
    
    if action == "1":
        # Record a new food price
        food_item = input("Enter the food item: ").strip()
        location = input("Enter the location (restaurant/store): ").strip()
        while True:
            try:
                price = float(input("Enter the price in USD: "))
                break
            except ValueError:
                print("Invalid input. Please enter a number.")
        
        now = datetime.now()
        date_str = now.strftime("%Y-%m-%d")
        time_str = now.strftime("%H:%M:%S")
        
        new_entry = {
            "date": date_str,
            "time": time_str,
            "food_item": food_item,
            "location": location,
            "price": price
        }
        entries.append(new_entry)
        
        with open("food_prices.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Food price recorded: {food_item} at {location} for ${price:.2f}")
    
    elif action == "2":
        # Look up past food prices and view statistics
        if not entries:
            print("No food price entries found. Please record a food price first.")
        else:
            lookup_type = input("Do you want to look up by (1) food item or (2) location? Enter 1 or 2: ").strip()
            
            if lookup_type == "1":
                # Look up by food item
                food_item = input("Enter the food item to look up: ").strip()
                matching_entries = [entry for entry in entries if entry["food_item"].lower() == food_item.lower()]
                
                if matching_entries:
                    print(f"\nEntries for {food_item}:")
                    for entry in matching_entries:
                        print(f"- {entry['date']} {entry['time']}: {entry['location']} - ${entry['price']:.2f}")
                    
                    # Find the cheapest spot for this food item
                    cheapest_entry = min(matching_entries, key=lambda x: x["price"])
                    print(f"\nCheapest spot for {food_item}: {cheapest_entry['location']} at ${cheapest_entry['price']:.2f}")
                else:
                    print(f"No entries found for {food_item}.")
            
            elif lookup_type == "2":
                # Look up by location
                location = input("Enter the location to look up: ").strip()
                matching_entries = [entry for entry in entries if entry["location"].lower() == location.lower()]
                
                if matching_entries:
                    print(f"\nEntries for {location}:")
                    for entry in matching_entries:
                        print(f"- {entry['date']} {entry['time']}: {entry['food_item']} - ${entry['price']:.2f}")
                    
                    # Calculate average price at this location
                    prices = [entry["price"] for entry in matching_entries]
                    avg_price = mean(prices)
                    print(f"\nAverage food price at {location}: ${avg_price:.2f}")
                    
                    # Find the cheapest food item at this location
                    cheapest_entry = min(matching_entries, key=lambda x: x["price"])
                    print(f"Cheapest food item at {location}: {cheapest_entry['food_item']} at ${cheapest_entry['price']:.2f}")
                else:
                    print(f"No entries found for {location}.")
            
            else:
                print("Invalid choice. Please enter 1 or 2.")
            
            # Overall best deal (cheapest food item overall)
            if entries:
                best_deal = min(entries, key=lambda x: x["price"])
                print(f"\nBest deal overall: {best_deal['food_item']} at {best_deal['location']} for ${best_deal['price']:.2f}")
    
    else:
        print("Invalid choice. Please run the script again and enter 1 or 2.")
  • Drink Price Tracker Python Script

    A Python script for recording and analyzing drink prices. Track your favorite cocktails, find the cheapest spots, and get insights like average prices per location and the best deal of the night.

    Click to view script…
    import json
    import os
    from datetime import datetime
    from statistics import mean
    
    # Load existing entries from the JSON file
    if os.path.exists("drink_prices.json"):
        with open("drink_prices.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new drink price or (2) look up past drink prices? Enter 1 or 2: ").strip()
    
    if action == "1":
        # Record a new drink price
        drink_name = input("Enter the drink name: ").strip()
        location = input("Enter the location (casino/bar): ").strip()
        while True:
            try:
                price = float(input("Enter the price in USD: "))
                break
            except ValueError:
                print("Invalid input. Please enter a number.")
        
        now = datetime.now()
        date_str = now.strftime("%Y-%m-%d")
        time_str = now.strftime("%H:%M:%S")
        
        new_entry = {
            "date": date_str,
            "time": time_str,
            "drink": drink_name,
            "location": location,
            "price": price
        }
        entries.append(new_entry)
        
        with open("drink_prices.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Drink price recorded: {drink_name} at {location} for ${price:.2f}")
    
    elif action == "2":
        # Look up past drink prices and view statistics
        if not entries:
            print("No drink price entries found. Please record a drink price first.")
        else:
            lookup_type = input("Do you want to look up by (1) drink name or (2) location? Enter 1 or 2: ").strip()
            
            if lookup_type == "1":
                # Look up by drink name
                drink_name = input("Enter the drink name to look up: ").strip()
                matching_entries = [entry for entry in entries if entry["drink"].lower() == drink_name.lower()]
                
                if matching_entries:
                    print(f"\nEntries for {drink_name}:")
                    for entry in matching_entries:
                        print(f"- {entry['date']} {entry['time']}: {entry['location']} - ${entry['price']:.2f}")
                    
                    # Find the cheapest spot for this drink
                    cheapest_entry = min(matching_entries, key=lambda x: x["price"])
                    print(f"\nCheapest spot for {drink_name}: {cheapest_entry['location']} at ${cheapest_entry['price']:.2f}")
                else:
                    print(f"No entries found for {drink_name}.")
            
            elif lookup_type == "2":
                # Look up by location
                location = input("Enter the location to look up: ").strip()
                matching_entries = [entry for entry in entries if entry["location"].lower() == location.lower()]
                
                if matching_entries:
                    print(f"\nEntries for {location}:")
                    for entry in matching_entries:
                        print(f"- {entry['date']} {entry['time']}: {entry['drink']} - ${entry['price']:.2f}")
                    
                    # Calculate average price at this location
                    prices = [entry["price"] for entry in matching_entries]
                    avg_price = mean(prices)
                    print(f"\nAverage drink price at {location}: ${avg_price:.2f}")
                    
                    # Find the cheapest drink at this location
                    cheapest_entry = min(matching_entries, key=lambda x: x["price"])
                    print(f"Cheapest drink at {location}: {cheapest_entry['drink']} at ${cheapest_entry['price']:.2f}")
                else:
                    print(f"No entries found for {location}.")
            
            else:
                print("Invalid choice. Please enter 1 or 2.")
            
            # Overall deal of the night (cheapest drink overall)
            if entries:
                deal_of_the_night = min(entries, key=lambda x: x["price"])
                print(f"\nDeal of the night: {deal_of_the_night['drink']} at {deal_of_the_night['location']} for ${deal_of_the_night['price']:.2f}")
    
    else:
        print("Invalid choice. Please run the script again and enter 1 or 2.")
  • Weight Tracking Python Script

    This Python script allows users to record their weight in pounds, automatically converting it to kilograms, and tracks entries over time with timestamps. It also enables users to look up past weights by date, showing changes from previous entries, and stores all data persistently in a JSON file for long-term tracking.

    Click to view script…
    import json
    import os
    from datetime import datetime
    
    def lbs_to_kg(lbs):
        """Convert weight from pounds to kilograms."""
        return lbs * 0.453592
    
    def validate_date(date_str):
        """Validate date input and return a date object if valid."""
        try:
            return datetime.strptime(date_str, "%Y-%m-%d").date()
        except ValueError:
            return None
    
    # Load existing entries from the JSON file
    if os.path.exists("weight_log.json"):
        with open("weight_log.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new weight or (2) look up a past weight? Enter 1 or 2: ").strip()
    
    if action == "1":
        # Record a new weight
        while True:
            try:
                weight = float(input("Enter your weight in pounds: "))
                break
            except ValueError:
                print("Invalid input. Please enter a number.")
        
        now = datetime.now()
        date_str = now.strftime("%Y-%m-%d")
        time_str = now.strftime("%H:%M:%S")
        
        if len(entries) > 0:
            previous_weight = entries[-1]["weight_lbs"]
            diff = weight - previous_weight
        else:
            diff = None
        
        new_entry = {"date": date_str, "time": time_str, "weight_lbs": weight}
        entries.append(new_entry)
        
        with open("weight_log.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Weight recorded: {weight:.2f} lbs ({lbs_to_kg(weight):.2f} kg)")
        
        if diff is not None:
            if diff > 0:
                print(f"You gained {diff:.2f} lbs ({lbs_to_kg(diff):.2f} kg) since the last entry.")
            elif diff < 0:
                print(f"You lost {-diff:.2f} lbs ({-lbs_to_kg(diff):.2f} kg) since the last entry.")
            else:
                print("No change in weight since the last entry.")
        else:
            print("This is your first entry. No previous data to compare.")
    
    elif action == "2":
        # Look up a past weight
        if not entries:
            print("No weight entries found. Please record a weight first.")
        else:
            while True:
                date_input = input("Enter the date to look up (YYYY-MM-DD): ")
                lookup_date = validate_date(date_input)
                if lookup_date:
                    break
                else:
                    print("Invalid date format. Please enter the date in YYYY-MM-DD format.")
            
            # Find entries for the specified date
            matching_entries = [entry for entry in entries if entry["date"] == date_input]
            
            if matching_entries:
                print(f"\nWeight entries for {date_input}:")
                for entry in matching_entries:
                    weight = entry["weight_lbs"]
                    time = entry["time"]
                    print(f"- {time}: {weight:.2f} lbs ({lbs_to_kg(weight):.2f} kg)")
            else:
                print(f"No weight entries found for {date_input}.")
    else:
        print("Invalid choice. Please run the script again and enter 1 or 2.")
  • Apple Product Spec Scraper Python Script

    This Python script searches Wikipedia for an Apple product by name, extracts key specifications like dimensions, weight, and camera details from the infobox, and formats the data for easy reading, with special handling for model-specific variations like “Pro” and “Pro Max.”

    This script relies on four Python libraries: requests fetches data from Wikipedia’s API, BeautifulSoup (from bs4) parses the HTML content to extract infobox details, sys handles command-line arguments for the product name input, and re provides regular expression support to clean up text by removing citation markers and extra whitespace. To install the external libraries, use pip: run pip install requests beautifulsoup4 in your terminal or command prompt, while sys and re are part of Python’s standard library and require no additional installation.

    Click to view script…
    import requests
    from bs4 import BeautifulSoup
    import sys
    import re
    
    # Define the fields we want to show
    desired_fields = [
        "First released",
        "Dimensions",
        "Weight",
        "Operating system",
        "System-on-chip",
        "Memory",
        "Storage",
        "Battery",
        "Rear camera",
        "Front camera",
        "Display",
    ]
    
    # Define fields that have model-specific values (e.g., Pro vs. Pro Max)
    model_specific_fields = ["Dimensions", "Weight", "Battery", "Display"]
    
    def search_wikipedia(query):
        """Search Wikipedia for the given query and return the title of the first result."""
        search_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "query",
            "list": "search",
            "srsearch": query,
            "format": "json"
        }
        response = requests.get(search_url, params=params)
        data = response.json()
        if data['query']['search']:
            return data['query']['search'][0]['title']
        return None
    
    def get_page_html(title):
        """Retrieve the HTML content of the Wikipedia page with the given title."""
        parse_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "parse",
            "page": title,
            "format": "json"
        }
        response = requests.get(parse_url, params=params)
        data = response.json()
        return data['parse']['text']['*']
    
    def extract_infobox(html):
        """Extract key-value pairs from the infobox in the HTML content."""
        soup = BeautifulSoup(html, 'html.parser')
        infobox = soup.find('table', {'class': 'infobox'})
        if infobox:
            rows = infobox.find_all('tr')
            info = {}
            for row in rows:
                header = row.find('th')
                data = row.find('td')
                if header and data:
                    key = header.text.strip()
                    value = data.text.strip()
                    info[key] = value
            return info
        return None
    
    def clean_text(text):
        """Remove citation numbers and extra spaces from the text."""
        return re.sub(r'\[\d+\]', '', text).strip()
    
    def format_model_values(value):
        """Format model-specific values for fields like dimensions, weight, etc."""
        if "Pro Max:" in value:
            pro_part, pro_max_part = value.split("Pro Max:", 1)
            pro_value = clean_text(pro_part.replace("Pro: ", "", 1).strip())
            pro_max_value = clean_text(pro_max_part.strip())
            return f"- Pro: {pro_value}\n- Pro Max: {pro_max_value}"
        elif "16 Pro Max:" in value:
            pro_part, pro_max_part = value.split("16 Pro Max:", 1)
            pro_value = clean_text(pro_part.replace("16 Pro: ", "", 1).strip())
            pro_max_value = clean_text(pro_max_part.strip())
            return f"- 16 Pro: {pro_value}\n- 16 Pro Max: {pro_max_value}"
        return clean_text(value)
    
    def main():
        if len(sys.argv) < 2:
            print("Usage: python3 apple_product_finder.py <product name>")
            sys.exit(1)
        product_name = " ".join(sys.argv[1:])
        title = search_wikipedia(product_name + " Apple")
        if not title:
            print("No product found.")
            return
        html = get_page_html(title)
        infobox = extract_infobox(html)
        if infobox:
            print(f"Key information for {title}:")
            for key in desired_fields:
                if key in infobox:
                    value = infobox[key]
                    if key in model_specific_fields:
                        formatted_value = format_model_values(value)
                        print(f"{key}:\n{formatted_value}")
                    else:
                        print(f"{key}: {clean_text(value)}")
        else:
            print("No infobox found for this product.")
    
    if __name__ == "__main__":
        main()
  • Earth–Mars Orbital Transfer Animation Python Script

    This Python script animates a simplified simulation of Earth and Mars orbiting the Sun along circular paths, while a spacecraft travels between them using a basic interpolation trajectory with a sinusoidal arc. It dynamically updates the planet positions and labels to clearly indicate which is Earth (blue) and which is Mars (red).

    This script uses NumPy for efficient numerical computations and trigonometric functions, and Matplotlib (including mpl_toolkits.mplot3d for 3D rendering and matplotlib.animation for dynamic visualizations) to animate the planetary orbits and spacecraft trajectory. To install these libraries, open your Terminal and run:

    pip install numpy matplotlib

    (Use pip3 if you’re working with Python 3.)

    Click to view script…
    #!/usr/bin/env python3
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D  # needed for 3D projection
    from matplotlib.animation import FuncAnimation
    
    # -----------------------------------------
    # 1) Orbital and Planetary Parameters
    # -----------------------------------------
    # Simplified units: 1 "unit" = 1 Astronomical Unit (AU)
    # Time is in days
    
    # Orbital radii (approx in AU)
    R_EARTH = 1.0
    R_MARS  = 1.52
    
    # Orbital periods (approx in days)
    T_EARTH = 365.0
    T_MARS  = 687.0
    
    # Angular velocities (radians per day)
    w_EARTH = 2.0 * np.pi / T_EARTH
    w_MARS  = 2.0 * np.pi / T_MARS
    
    # Initial phases (starting positions)
    phi_earth0 = 0.0
    phi_mars0  = 0.0
    
    # Radii of the planets (for plotting spheres)
    EARTH_RADIUS = 0.05
    MARS_RADIUS  = 0.03
    
    # -----------------------------------------
    # 2) Define Planet Position Functions
    # -----------------------------------------
    def planet_position(time, R, omega, phi0=0.0):
        """
        Returns the (x, y, z) position of a planet orbiting in the XY plane.
        """
        x = R * np.cos(omega * time + phi0)
        y = R * np.sin(omega * time + phi0)
        z = 0.0
        return np.array([x, y, z])
    
    # -----------------------------------------
    # 3) Spacecraft Trajectory
    # -----------------------------------------
    def find_launch_day(t_range):
        """
        Finds a launch day in t_range where the Earth-Mars distance is minimized.
        """
        best_day = None
        min_dist = 1e9
        for t in t_range:
            earth_pos = planet_position(t, R_EARTH, w_EARTH, phi_earth0)
            mars_pos  = planet_position(t, R_MARS,  w_MARS,  phi_mars0)
            dist = np.linalg.norm(mars_pos - earth_pos)
            if dist < min_dist:
                min_dist = dist
                best_day = t
        return best_day
    
    def spacecraft_trajectory(t, t_launch, t_arrival, home_func, target_func):
        """
        Computes a simple interpolated trajectory between two planets.
        Outside the travel window, it holds the departure or arrival position.
        """
        if t <= t_launch:
            return home_func(t_launch)
        elif t >= t_arrival:
            return target_func(t_arrival)
        else:
            # Fraction of travel completed
            frac = (t - t_launch) / (t_arrival - t_launch)
            pos_home = home_func(t_launch)
            pos_target = target_func(t_arrival)
            # Add a sinusoidal 'arc' in the Z direction for visual flair
            arc_height = 0.2 * np.sin(np.pi * frac)
            interp = (1 - frac) * pos_home + frac * pos_target
            interp[2] += arc_height
            return interp
    
    # -----------------------------------------
    # 4) Set Up the Animation Plot
    # -----------------------------------------
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot(111, projection='3d')
    
    # Function to draw a sphere (used for Earth and Mars)
    def plot_sphere(ax, center, radius, color, alpha=1.0):
        u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
        x = center[0] + radius * np.cos(u) * np.sin(v)
        y = center[1] + radius * np.sin(u) * np.sin(v)
        z = center[2] + radius * np.cos(v)
        ax.plot_surface(x, y, z, color=color, alpha=alpha)
    
    # Global variables to store our plot elements
    earth_surf = None
    mars_surf = None
    spacecraft_marker, = ax.plot([], [], [], 'go', markersize=6)
    earth_label = None
    mars_label = None
    
    # Time settings for the simulation (e.g., 1200 days)
    total_frames = 1000
    times = np.linspace(0, 1200, total_frames)
    
    # Find a simplistic launch day within the first 300 days
    launch_day = find_launch_day(range(300))
    travel_time = 180.0  # days for Earth-to-Mars travel
    arrival_day = launch_day + travel_time
    
    # Return trip parameters (optional)
    stay_time_on_mars = 100.0
    return_launch_day = arrival_day + stay_time_on_mars
    return_arrival_day = return_launch_day + 200.0
    
    # Utility to get the x, y, z coordinates for a sphere surface
    def _sphere_xyz(center, radius, n_u=20, n_v=10):
        u = np.linspace(0, 2*np.pi, n_u)
        v = np.linspace(0, np.pi, n_v)
        u, v = np.meshgrid(u, v)
        x = center[0] + radius * np.cos(u) * np.sin(v)
        y = center[1] + radius * np.sin(u) * np.sin(v)
        z = center[2] + radius * np.cos(v)
        return x, y, z
    
    # -----------------------------------------
    # 5) Animation Update Function
    # -----------------------------------------
    def update(frame):
        global earth_surf, mars_surf, earth_label, mars_label
    
        # Current time in days
        t = times[frame]
    
        # Update positions for Earth and Mars
        earth_pos = planet_position(t, R_EARTH, w_EARTH, phi_earth0)
        mars_pos  = planet_position(t, R_MARS,  w_MARS,  phi_mars0)
    
        # Remove old spheres if they exist
        if earth_surf is not None:
            earth_surf.remove()
        if mars_surf is not None:
            mars_surf.remove()
    
        # Plot new spheres for Earth and Mars
        earth_surf = ax.plot_surface(*_sphere_xyz(earth_pos, EARTH_RADIUS),
                                     color='blue', alpha=0.6)
        mars_surf = ax.plot_surface(*_sphere_xyz(mars_pos, MARS_RADIUS),
                                    color='red', alpha=0.6)
        
        # Remove old labels if they exist
        if earth_label is not None:
            earth_label.remove()
        if mars_label is not None:
            mars_label.remove()
        
        # Add new text labels above each planet
        earth_label = ax.text(earth_pos[0], earth_pos[1], earth_pos[2] + EARTH_RADIUS + 0.05,
                              'Earth', color='blue', fontsize=10, weight='bold')
        mars_label = ax.text(mars_pos[0], mars_pos[1], mars_pos[2] + MARS_RADIUS + 0.05,
                             'Mars', color='red', fontsize=10, weight='bold')
        
        # Update spacecraft position based on current time
        if t < return_launch_day:
            # Outbound: Earth to Mars
            sc_pos = spacecraft_trajectory(t, launch_day, arrival_day,
                                           lambda tau: planet_position(tau, R_EARTH, w_EARTH, phi_earth0),
                                           lambda tau: planet_position(tau, R_MARS,  w_MARS,  phi_mars0))
        else:
            # Return: Mars to Earth
            sc_pos = spacecraft_trajectory(t, return_launch_day, return_arrival_day,
                                           lambda tau: planet_position(tau, R_MARS, w_MARS, phi_mars0),
                                           lambda tau: planet_position(tau, R_EARTH, w_EARTH, phi_earth0))
        
        # Update the spacecraft marker (green dot)
        spacecraft_marker.set_data([sc_pos[0]], [sc_pos[1]])
        spacecraft_marker.set_3d_properties([sc_pos[2]])
        
        # Return all updated artists
        return earth_surf, mars_surf, spacecraft_marker, earth_label, mars_label
    
    # -----------------------------------------
    # 6) Plot Aesthetics and Animation Setup
    # -----------------------------------------
    ax.set_xlim(-1.6, 1.6)
    ax.set_ylim(-1.6, 1.6)
    ax.set_zlim(-0.6, 0.6)
    ax.set_xlabel('X (AU)')
    ax.set_ylabel('Y (AU)')
    ax.set_zlabel('Z')
    ax.set_title('Earth–Mars Orbits with Spacecraft Launch')
    
    # Draw the Sun at the origin as a yellow sphere
    plot_sphere(ax, [0, 0, 0], 0.1, 'yellow', alpha=0.9)
    
    # Create the animation
    anim = FuncAnimation(fig, update, frames=total_frames, interval=30, blit=False)
    
    plt.show()
  • Advanced Password Strength Checker Python Script

    This script assesses the security of any given password by checking its length, character diversity, and commonality, then provides a strength score along with detailed improvement suggestions if needed. It also explains why a password is strong when it meets all the criteria.

    Click to view script…
    #!/usr/bin/env python3
    import re
    import getpass
    
    def evaluate_password_strength(password):
        """
        Evaluate the password strength based on five criteria:
        - At least 8 characters long
        - Contains an uppercase letter
        - Contains a lowercase letter
        - Contains a digit
        - Contains a special character
        Additionally, the function checks for commonly used (and easily guessable) passwords.
        Returns a tuple containing the strength rating, score, and suggestions for improvement.
        """
        score = 0
        suggestions = []
    
        # Check for common (easily guessable) passwords
        common_passwords = {
            "password", "12345", "123456", "qwerty", "abc123",
            "111111", "123123", "password1", "letmein", "admin"
        }
        if password.lower() in common_passwords:
            suggestions.append("Your password is among the most commonly used and easily guessable passwords. Please choose a more unique password.")
            # Override the score for common passwords
            score = 0
            # Early return the evaluation since it's a significant security risk.
            return "Weak", score, suggestions
    
        # Check for minimum length
        if len(password) >= 8:
            score += 1
        else:
            suggestions.append("Make sure your password is at least 8 characters long.")
    
        # Check for uppercase letters
        if re.search(r'[A-Z]', password):
            score += 1
        else:
            suggestions.append("Include at least one uppercase letter.")
    
        # Check for lowercase letters
        if re.search(r'[a-z]', password):
            score += 1
        else:
            suggestions.append("Include at least one lowercase letter.")
    
        # Check for digits
        if re.search(r'\d', password):
            score += 1
        else:
            suggestions.append("Include at least one digit.")
    
        # Check for special characters
        if re.search(r'[\W_]', password):
            score += 1
        else:
            suggestions.append("Include at least one special character.")
    
        # Determine strength rating based on the score
        if score <= 2:
            strength = "Weak"
        elif score in [3, 4]:
            strength = "Moderate"
        else:
            strength = "Strong"
    
        return strength, score, suggestions
    
    def main():
        print("Password Strength Checker")
        # Using getpass to hide input for privacy; replace with input() if needed.
        password = getpass.getpass("Enter a password to evaluate: ")
        
        strength, score, suggestions = evaluate_password_strength(password)
        
        print(f"\nPassword Strength: {strength}")
        print(f"Score: {score} out of 5")
        
        if score == 5:
            print("\nExplanation: This password is strong because it meets all the required criteria: it is at least 8 characters long, includes both uppercase and lowercase letters, contains at least one digit, and has at least one special character.")
        elif suggestions:
            print("\nSuggestions for improvement:")
            for suggestion in suggestions:
                print(f" - {suggestion}")
    
    if __name__ == '__main__':
        main()