Blog

  • Largest Files Explorer with Interactive Details PowerShell Script

    This PowerShell script scans a specified directory for files, lists the largest files in a neat, truncated table, and lets you view full details for any selected file or all files, providing a comprehensive yet user-friendly overview of disk usage.

    Click to view script…
    <#
    .SYNOPSIS
        Lists the largest files in a directory with a truncated display and full detail lookup.
    
    .DESCRIPTION
        This script recursively scans a specified directory (or the current directory by default),
        sorts all files by size in descending order, and displays the top N largest files as specified by the user.
        It shows a truncated file name and full path for a neat table view.
        After displaying the table, the user can choose an index (or "all") to view full details of the file(s).
    
    .NOTES
        Run as Administrator if scanning protected directories.
    #>
    
    # Function to convert bytes to a human-readable format.
    function Convert-BytesToHumanReadable {
        param ([long]$bytes)
        if ($bytes -ge 1PB) {
            return "{0:N2} PB" -f ($bytes / 1PB)
        }
        elseif ($bytes -ge 1TB) {
            return "{0:N2} TB" -f ($bytes / 1TB)
        }
        elseif ($bytes -ge 1GB) {
            return "{0:N2} GB" -f ($bytes / 1GB)
        }
        elseif ($bytes -ge 1MB) {
            return "{0:N2} MB" -f ($bytes / 1MB)
        }
        elseif ($bytes -ge 1KB) {
            return "{0:N2} KB" -f ($bytes / 1KB)
        }
        else {
            return "$bytes B"
        }
    }
    
    # Function to truncate long strings.
    function Truncate-String {
        param (
            [Parameter(Mandatory = $true)]
            [string]$str,
            [int]$maxLength = 50
        )
        if ($str.Length -gt $maxLength) {
            return $str.Substring(0, $maxLength - 3) + "..."
        }
        else {
            return $str
        }
    }
    
    # Prompt the user for the directory to scan (default is current directory).
    $directory = Read-Host "Enter the directory to scan (or press Enter for current directory)"
    if ([string]::IsNullOrWhiteSpace($directory)) {
        $directory = (Get-Location).Path
    }
    
    if (-not (Test-Path $directory)) {
        Write-Error "Directory '$directory' does not exist."
        exit
    }
    
    # Prompt the user for the number of items to list.
    $numberOfItems = Read-Host "Enter the number of largest files to list"
    if (-not [int]::TryParse($numberOfItems, [ref]$null)) {
        Write-Error "Invalid number entered. Please enter a valid integer."
        exit
    }
    $numberOfItems = [int]$numberOfItems
    
    Write-Host "Scanning directory '$directory' for files..." -ForegroundColor Cyan
    
    # Recursively retrieve all files within the specified directory.
    try {
        $files = Get-ChildItem -Path $directory -File -Recurse -ErrorAction SilentlyContinue
    } catch {
        Write-Error "Error retrieving files: $_"
        exit
    }
    
    if (!$files) {
        Write-Host "No files found in '$directory'."
        exit
    }
    
    # Sort the files by size (Length) descending and take the top N items.
    $largestFiles = $files | Sort-Object Length -Descending | Select-Object -First $numberOfItems
    
    # Build a table with an index and truncated file name and path.
    $i = 1
    $result = foreach ($file in $largestFiles) {
        [PSCustomObject]@{
            Index         = $i
            "File Name"   = Truncate-String -str $file.Name -maxLength 30
            "Full Path"   = Truncate-String -str $file.FullName -maxLength 60
            "Size (Bytes)"= $file.Length
            "Size (Human)"= Convert-BytesToHumanReadable -bytes $file.Length
        }
        $i++
    }
    
    # Display the results in a formatted table.
    Write-Host "`nTop $numberOfItems largest files in '$directory':" -ForegroundColor Green
    $result | Format-Table -AutoSize
    
    # Allow the user to view full details if needed.
    $choice = Read-Host "`nEnter a file index to view full details, type 'all' to view details for all files, or press Enter to exit"
    if (-not [string]::IsNullOrWhiteSpace($choice)) {
        if ($choice -match '^(all)$') {
            Write-Host "`nFull details for all files:" -ForegroundColor Cyan
            $largestFiles | Format-List *
        }
        elseif ([int]::TryParse($choice, [ref]$null)) {
            $index = [int]$choice
            if ($index -ge 1 -and $index -le $largestFiles.Count) {
                Write-Host "`nFull details for file at index $($index):" -ForegroundColor Cyan
                $largestFiles[$index - 1] | Format-List *
            }
            else {
                Write-Host "Invalid index entered." -ForegroundColor Yellow
            }
        }
    }
  • DNS Ping Test Utility PowerShell Script

    This PowerShell script allows users to select from a list of popular DNS servers and perform customizable ping tests to verify network connectivity. It supports both continuous and fixed-count pings, configurable intervals, optional logging, and displays summary statistics for comprehensive network diagnostics.

    Click to view script…
    <#
    .SYNOPSIS
        DNS Ping Test Utility
    
    .DESCRIPTION
        This script allows the user to choose from a list of popular DNS servers (e.g., Google, Cloudflare, OpenDNS, etc.)
        and then performs either continuous or fixed-count ping tests to verify network connectivity.
        Users can configure the interval between pings and optionally log the results to a file for further analysis.
        
    .NOTES
        Press Ctrl+C to exit continuous ping mode.
    #>
    
    # Define a list of DNS providers.
    $dnsProviders = @(
        [PSCustomObject]@{Name="Google DNS";       IP="8.8.8.8"},
        [PSCustomObject]@{Name="Cloudflare DNS";   IP="1.1.1.1"},
        [PSCustomObject]@{Name="OpenDNS";          IP="208.67.222.222"},
        [PSCustomObject]@{Name="Quad9 DNS";        IP="9.9.9.9"},
        [PSCustomObject]@{Name="Level3 DNS";       IP="4.2.2.2"}
    )
    
    # Display the DNS server options.
    Write-Host "Select a DNS server to ping:" -ForegroundColor Cyan
    for ($i = 0; $i -lt $dnsProviders.Count; $i++) {
        Write-Host ("{0}. {1} ({2})" -f ($i + 1), $dnsProviders[$i].Name, $dnsProviders[$i].IP)
    }
    
    # Prompt the user to choose a DNS server.
    [int]$choice = Read-Host "Enter the number corresponding to your choice"
    if ($choice -lt 1 -or $choice -gt $dnsProviders.Count) {
        Write-Error "Invalid selection. Exiting."
        exit
    }
    
    $selectedDNS = $dnsProviders[$choice - 1]
    Write-Host "You selected: $($selectedDNS.Name) ($($selectedDNS.IP))" -ForegroundColor Green
    
    # Ask if the user wants a fixed number of pings or continuous ping.
    $pingCountInput = Read-Host "Enter number of pings (or press Enter for continuous ping)"
    if ($pingCountInput -match '^\d+$') {
        $pingCount = [int]$pingCountInput
        $isContinuous = $false
    } else {
        $isContinuous = $true
    }
    
    # Ask for the interval between pings in seconds.
    $intervalInput = Read-Host "Enter interval in seconds between pings (default is 1 second)"
    if ([string]::IsNullOrWhiteSpace($intervalInput)) {
        $interval = 1
    } else {
        $interval = [double]$intervalInput
    }
    
    # Ask if the user wants to log the results to a file.
    $logChoice = Read-Host "Do you want to log results to a file? (Y/N)"
    $logEnabled = $false
    if ($logChoice -match '^[Yy]') {
        $logEnabled = $true
        $logFile = Read-Host "Enter log file path (or press Enter for default 'DNSPingLog.txt')"
        if ([string]::IsNullOrWhiteSpace($logFile)) {
            $logFile = "DNSPingLog.txt"
        }
        Write-Host "Logging enabled. Results will be saved to $logFile" -ForegroundColor Green
    }
    
    # Initialize an array to store successful ping response times if a fixed ping count is specified.
    if (-not $isContinuous) {
        $results = @()
    }
    
    Write-Host "Starting ping test to $($selectedDNS.IP)..." -ForegroundColor Cyan
    
    # Function to log output if logging is enabled.
    function Log-Output {
        param (
            [string]$message
        )
        if ($logEnabled) {
            $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            Add-Content -Path $logFile -Value "[$timestamp] $message"
        }
    }
    
    # Run the ping test.
    if ($isContinuous) {
        Write-Host "Press Ctrl+C to stop continuous ping."
        while ($true) {
            try {
                $pingResult = Test-Connection -ComputerName $selectedDNS.IP -Count 1 -ErrorAction SilentlyContinue
                $timestamp = Get-Date -Format "HH:mm:ss"
                if ($pingResult) {
                    $replyTime = $pingResult.ResponseTime
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Reply from $($selectedDNS.IP): time = $replyTime ms"
                } else {
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Request timed out for $($selectedDNS.IP)."
                }
                Write-Host $output
                Log-Output -message $output
            }
            catch {
                Write-Host "An error occurred: $_"
                Log-Output -message "Error: $_"
            }
            Start-Sleep -Seconds $interval
        }
    } else {
        for ($i = 1; $i -le $pingCount; $i++) {
            try {
                $pingResult = Test-Connection -ComputerName $selectedDNS.IP -Count 1 -ErrorAction SilentlyContinue
                $timestamp = Get-Date -Format "HH:mm:ss"
                if ($pingResult) {
                    $replyTime = $pingResult.ResponseTime
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Reply from $($selectedDNS.IP): time = $replyTime ms"
                    $results += $replyTime
                } else {
                    $output = "[$timestamp] Ping $($i)/$($pingCount): Request timed out for $($selectedDNS.IP)."
                }
                Write-Host $output
                Log-Output -message $output
            }
            catch {
                Write-Host "An error occurred: $_"
                Log-Output -message "Error: $_"
            }
            Start-Sleep -Seconds $interval
        }
        
        # Provide summary statistics for the fixed-count ping test.
        if ($results.Count -gt 0) {
            $avgTime = [Math]::Round(($results | Measure-Object -Average).Average, 2)
            Write-Host "`nPing test completed. Average response time: $avgTime ms" -ForegroundColor Green
            Log-Output -message "Ping test completed. Average response time: $avgTime ms"
        } else {
            Write-Host "`nPing test completed. No successful pings." -ForegroundColor Yellow
            Log-Output -message "Ping test completed. No successful pings."
        }
    }
  • User Account Audit with Net User Parsing PowerShell Script

    This PowerShell script audits local user accounts by listing each account’s enabled/disabled status and extracting detailed last logon information using the net user command. It outputs a neatly formatted table, providing system administrators with a clear snapshot of user account activity for easier monitoring and troubleshooting.

    Click to view script…
    <#
    .SYNOPSIS
        Audits local user accounts by listing their enabled/disabled status and last logon time.
    
    .DESCRIPTION
        This script retrieves local user accounts using Get-LocalUser and then obtains last logon information
        for each account by parsing the output of the "net user" command. It outputs a table showing each account's name,
        whether it is enabled, and its last logon time (or "Never" if the account has not logged on).
    
    .NOTES
        Run as Administrator if necessary.
    #>
    
    function Get-LastLogonNetUser {
        param (
            [Parameter(Mandatory = $true)]
            [string]$UserName
        )
    
        # Execute the "net user" command for the given user
        $netUserOutput = net user $UserName 2>&1
    
        # Look for a line that contains "Last logon"
        $lastLogonLine = $netUserOutput | Where-Object { $_ -match "Last logon" }
        if ($lastLogonLine) {
            # The expected format is something like:
            #   Last logon                   2/12/2021 3:45:30 PM
            # Remove the label text and trim spaces to isolate the date/time string.
            $logonValue = ($lastLogonLine -replace ".*Last logon\s+", "").Trim()
            if ($logonValue -match "Never") {
                return "Never"
            }
            else {
                # Attempt to parse the logon value as a DateTime.
                try {
                    $dt = [DateTime]::Parse($logonValue)
                    return $dt
                }
                catch {
                    return $logonValue
                }
            }
        }
        else {
            return "Unknown"
        }
    }
    
    # Retrieve local user accounts.
    try {
        $localUsers = Get-LocalUser
    } catch {
        Write-Error "Failed to retrieve local users. Ensure this is run on a supported version of Windows with appropriate permissions."
        exit
    }
    
    # Prepare an array to store the audit results.
    $result = @()
    
    foreach ($user in $localUsers) {
        $userName = $user.Name
        $lastLogon = Get-LastLogonNetUser -UserName $userName
    
        $result += [PSCustomObject]@{
            Name      = $userName
            Enabled   = $user.Enabled
            LastLogon = $lastLogon
        }
    }
    
    # Output the results in a formatted table.
    $result | Format-Table -AutoSize
  • Rock, Paper, Scissors JavaScript Game

    This Node.js script lets you challenge the computer in a classic match of Rock, Paper, Scissors. Simply enter your move, and the computer will randomly choose its move, with the game determining the winner based on standard rules.

    Click to view script…
    /*
     * Rock, Paper, Scissors Game
     *
     * Instructions:
     *   1. Enter your move: "rock", "paper", or "scissors".
     *   2. The computer will randomly choose its move.
     *   3. The game will then announce the winner:
     *      - Rock crushes scissors.
     *      - Scissors cuts paper.
     *      - Paper covers rock.
     *
     * Enjoy the game!
     */
    
    const readline = require('readline');
    
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    const choices = ["rock", "paper", "scissors"];
    
    // Function to randomly select the computer's choice
    function getComputerChoice() {
      const randomIndex = Math.floor(Math.random() * choices.length);
      return choices[randomIndex];
    }
    
    // Function to determine the result of the game
    function getResult(userChoice, computerChoice) {
      if (userChoice === computerChoice) {
        return "It's a tie!";
      }
      if (userChoice === "rock") {
        return computerChoice === "scissors" ? "You win! Rock crushes scissors." : "You lose! Paper covers rock.";
      }
      if (userChoice === "paper") {
        return computerChoice === "rock" ? "You win! Paper covers rock." : "You lose! Scissors cuts paper.";
      }
      if (userChoice === "scissors") {
        return computerChoice === "paper" ? "You win! Scissors cuts paper." : "You lose! Rock crushes scissors.";
      }
    }
    
    // Main game loop
    function playGame() {
      rl.question("Enter your move (rock, paper, or scissors): ", (answer) => {
        let userChoice = answer.trim().toLowerCase();
        if (!choices.includes(userChoice)) {
          console.log("Invalid move. Please choose rock, paper, or scissors.");
          return playGame();
        }
        const computerChoice = getComputerChoice();
        console.log(`Computer chose: ${computerChoice}`);
        const result = getResult(userChoice, computerChoice);
        console.log(result);
        rl.question("Play again? (yes/no): ", (response) => {
          if (response.trim().toLowerCase().startsWith("y")) {
            playGame();
          } else {
            console.log("Thanks for playing!");
            rl.close();
          }
        });
      });
    }
    
    console.log("=== Rock, Paper, Scissors Game ===");
    playGame();
  • Reverse Word Puzzle JavaScript Game

    This script randomly selects a word from a list, reverses it, and challenges the player to guess the original word. It demonstrates basic Node.js functionality, including using the readline module for handling terminal input.

    Click to view script…
    // reverseWordPuzzle.js
    
    // List of words for the puzzle
    const words = ['apple', 'banana', 'orange', 'strawberry', 'grape', 'pineapple', 'kiwi'];
    
    // Function to reverse a given word
    function reverseWord(word) {
      return word.split('').reverse().join('');
    }
    
    // Function to pick a random word from the array
    function getRandomWord() {
      return words[Math.floor(Math.random() * words.length)];
    }
    
    // Main function to run the game
    function playGame() {
      const originalWord = getRandomWord();
      const reversedWord = reverseWord(originalWord);
      
      console.log("=== Reverse Word Puzzle ===");
      console.log(`Unscramble this reversed word: ${reversedWord}`);
    
      // Create an interface for user input
      const readline = require('readline');
      const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
      });
    
      // Ask the user for their guess
      rl.question("Your guess: ", (answer) => {
        if(answer.trim().toLowerCase() === originalWord.toLowerCase()){
          console.log("Correct! Well done.");
        } else {
          console.log(`Incorrect. The correct word was: ${originalWord}`);
        }
        rl.close();
      });
    }
    
    // Start the game
    playGame();
  • 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()
    
  • Retrieve Weather for Any City Python Script

    This Python script fetches current weather data for a specified city from wttr.in, converts the temperature to Fahrenheit, and displays the weather condition along with humidity. It provides a quick and API-key-free way to get up-to-date weather information right from your command line.

    Click to view script…
    #!/usr/bin/env python3
    import requests
    
    def get_weather(city):
        url = f"http://wttr.in/{city}?format=j1"
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
    
            # Extract current weather information
            current = data['current_condition'][0]
            temp_c = float(current.get('temp_C', 0))
            temp_f = (temp_c * 9/5) + 32  # Convert Celsius to Fahrenheit
            weather_desc = current.get('weatherDesc', [{}])[0].get('value', 'No description')
            humidity = current.get('humidity')
    
            print(f"\nWeather in {city.title()}:")
            print(f"  Temperature: {temp_f:.1f}°F")
            print(f"  Condition: {weather_desc}")
            print(f"  Humidity: {humidity}%")
        except requests.exceptions.RequestException as e:
            print("Error: Could not retrieve weather data.")
            print(e)
    
    if __name__ == "__main__":
        city = input("Enter a city name: ")
        get_weather(city)
    
  • Virtual Pet Simulator Python Script

    A simple virtual pet game where you can feed, play with, and put your pet to sleep—keep it happy and healthy or watch things go south.

    Click to view script…
    import time
    
    class VirtualPet:
        def __init__(self, name):
            self.name = name
            self.hunger = 5      # 0 means full, 10 means starving
            self.happiness = 5   # 0 means sad, 10 means happy
            self.energy = 5      # 0 means tired, 10 means full of energy
            self.alive = True
    
        def feed(self):
            if self.hunger > 0:
                self.hunger -= 1
                print(f"You fed {self.name}. Hunger is now {self.hunger}/10.")
            else:
                print(f"{self.name} isn't hungry right now!")
    
        def play(self):
            if self.energy > 0:
                self.happiness = min(10, self.happiness + 1)
                self.energy -= 1
                self.hunger = min(10, self.hunger + 1)
                print(f"You played with {self.name}. Happiness: {self.happiness}/10, Energy: {self.energy}/10, Hunger: {self.hunger}/10.")
            else:
                print(f"{self.name} is too tired to play.")
    
        def sleep(self):
            print(f"{self.name} is sleeping...")
            time.sleep(2)
            self.energy = min(10, self.energy + 3)
            self.hunger = min(10, self.hunger + 1)
            print(f"{self.name} woke up. Energy: {self.energy}/10, Hunger: {self.hunger}/10.")
    
        def status(self):
            print(f"\n{self.name}'s Status:")
            print(f"  Hunger: {self.hunger}/10")
            print(f"  Happiness: {self.happiness}/10")
            print(f"  Energy: {self.energy}/10")
    
        def update(self):
            # Stats change over time
            self.hunger = min(10, self.hunger + 1)
            self.happiness = max(0, self.happiness - 1)
            self.energy = max(0, self.energy - 1)
            if self.hunger == 10 or self.happiness == 0 or self.energy == 0:
                self.alive = False
                print(f"\nSadly, {self.name} has passed away due to neglect...")
    
    def main():
        pet_name = input("Name your pet: ")
        pet = VirtualPet(pet_name)
        print(f"Welcome, {pet.name}!")
        
        while pet.alive:
            pet.status()
            print("\nActions: feed | play | sleep | exit")
            action = input("What do you want to do? ").strip().lower()
            
            if action == "feed":
                pet.feed()
            elif action == "play":
                pet.play()
            elif action == "sleep":
                pet.sleep()
            elif action == "exit":
                print("Goodbye!")
                break
            else:
                print("Invalid action. Try again.")
            
            pet.update()
        
        print("Game over.")
    
    if __name__ == '__main__':
        main()