Category: Python

  • 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()
    
  • Matrix Rain Effect Python Script

    This Python script simulates the iconic digital rain from The Matrix in your terminal using the curses library. Green characters cascade down your screen, and press any key to exit the mesmerizing effect.

    Click to view script…
    import curses
    import random
    import time
    
    def matrix_rain(stdscr):
        # Hide the cursor and set non-blocking input
        curses.curs_set(0)
        stdscr.nodelay(True)
        stdscr.timeout(50)
        
        # Initialize colors if supported
        if curses.has_colors():
            curses.start_color()
            curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    
        sh, sw = stdscr.getmaxyx()  # Get screen height and width
        # Initialize each column with a random starting row
        columns = [random.randint(0, sh - 1) for _ in range(sw)]
    
        while True:
            stdscr.erase()  # Clear the screen for fresh drawing
            for x in range(sw):
                y = columns[x]
                # Generate a random printable ASCII character
                char = chr(random.randint(33, 126))
                try:
                    if curses.has_colors():
                        stdscr.addch(y, x, char, curses.color_pair(1))
                    else:
                        stdscr.addch(y, x, char)
                except curses.error:
                    # Ignore errors when drawing outside of the screen bounds
                    pass
    
                # Move the column down; reset to the top if at the bottom
                columns[x] = y + 1 if y < sh - 1 else 0
    
            stdscr.refresh()
            time.sleep(0.05)  # Adjust the speed of the rain
    
            # Exit the loop if any key is pressed
            if stdscr.getch() != -1:
                break
    
    def main():
        curses.wrapper(matrix_rain)
    
    if __name__ == '__main__':
        main()
  • Customizable Python Countdown Timer

    This Python script lets users set their own countdown duration by entering the number of seconds. It validates the input and displays a live timer until it reaches zero, announcing when time is up.

    Click to view script…
    import time
    
    def countdown(seconds):
        while seconds:
            mins, secs = divmod(seconds, 60)
            timer = '{:02d}:{:02d}'.format(mins, secs)
            print(timer, end="\r")
            time.sleep(1)
            seconds -= 1
        print("Time's up!")
    
    try:
        user_input = int(input("Enter the number of seconds for the countdown: "))
        countdown(user_input)
    except ValueError:
        print("Invalid input. Please enter an integer value.")
  • Random Python Password Generator

    This script generates a secure, random password using a mix of letters, digits, and punctuation.

    Click to view script…
    import random
    import string
    
    def generate_password(length=12):
        characters = string.ascii_letters + string.digits + string.punctuation
        password = ''.join(random.choice(characters) for _ in range(length))
        return password
    
    print("Your new password is:", generate_password())