diff --git a/Number_Guessing/Number-guesser/Number_guesser.py b/Number_Guessing/Number-guesser/Number_guesser.py new file mode 100644 index 00000000..a4ee4590 --- /dev/null +++ b/Number_Guessing/Number-guesser/Number_guesser.py @@ -0,0 +1,54 @@ +import random + +def play_game(): + random_num = random.randint(1, 100) + guesses = 0 + while True: + try: + user = input(f"Guess #{guesses + 1} (1-100) or 'q' to quit: ").strip() + except (EOFError, KeyboardInterrupt): + print("\nExiting game.") + return False + + if user.lower() == 'q': + print("Quitting current game.") + return False + + try: + guess = int(user) + except ValueError: + print("Please enter a valid integer between 1 and 100, or 'q' to quit.") + continue + + if not 1 <= guess <= 100: + print("Please guess a number between 1 and 100.") + continue + + guesses += 1 + + if guess == random_num: + plural = "guess" if guesses == 1 else "guesses" + print(f"You won in {guesses} {plural}! The number was {random_num}.") + return True + elif guess > random_num: + print("Your guess is too high.") + else: + print("Your guess is too low.") + +def main(): + while True: + play_game() + try: + answer = input("Would you like to play again? (Y/N): ").strip().lower() + except (EOFError, KeyboardInterrupt): + print("\nGoodbye.") + return + if answer in ('n', 'no'): + print("Thanks for playing. Goodbye.") + return + if answer in ('y', 'yes'): + continue + print("Please answer Y or N.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Number_Guessing/Number-guesser/README.md b/Number_Guessing/Number-guesser/README.md new file mode 100644 index 00000000..3d99f4f1 --- /dev/null +++ b/Number_Guessing/Number-guesser/README.md @@ -0,0 +1 @@ +Simple CLI game: guess a random number (1–100), get feedback (too high/low), type `q` to quit. \ No newline at end of file diff --git a/VOICE_RECORDER/Simple _interactive_audio_recorder.py b/VOICE_RECORDER/Simple _interactive_audio_recorder.py new file mode 100644 index 00000000..caa61bcf --- /dev/null +++ b/VOICE_RECORDER/Simple _interactive_audio_recorder.py @@ -0,0 +1,58 @@ +import sounddevice as sd +import wavio +import os +import time + +def list_input_devices(): + try: + devices = sd.query_devices() + print("Available audio devices:") + for i, dev in enumerate(devices): + print(f"{i}: {dev['name']} (max input channels: {dev.get('max_input_channels', 0)})") + except Exception as e: + print("Could not query devices:", e) + +def record_audio(duration, filename, samplerate=44100, channels=2, dtype='int16', device=None): + if not filename.lower().endswith('.wav'): + filename += '.wav' + try: + frames = int(duration * samplerate) + print(f"Recording for {duration} seconds (samplerate={samplerate}, channels={channels})...") + start = time.time() + audio = sd.rec(frames, samplerate=samplerate, channels=channels, dtype=dtype, device=device) + sd.wait() + elapsed = time.time() - start + # Ensure output directory exists + out_dir = os.path.dirname(os.path.abspath(filename)) + if out_dir and not os.path.exists(out_dir): + os.makedirs(out_dir, exist_ok=True) + wavio.write(filename, audio, samplerate, sampwidth=2) + print(f"Recording saved as '{filename}' ({elapsed:.2f}s)") + except KeyboardInterrupt: + print("\nRecording cancelled by user.") + except Exception as e: + print("Recording failed:", e) + +if __name__ == "__main__": + try: + print("Press Enter to see available input devices or type 'skip' to continue with default device.") + if input().strip().lower() != 'skip': + list_input_devices() + + device_input = input("Enter device index to use (or press Enter for default): ").strip() + device = int(device_input) if device_input != '' else None + + record_duration = float(input("Enter duration in seconds: ").strip()) + file_name = input("Enter filename (with or without .wav extension) [default: recording.wav]: ").strip() or "recording.wav" + + sr_input = input("Enter sample rate (default 44100): ").strip() + samplerate = int(sr_input) if sr_input else 44100 + + ch_input = input("Enter number of channels (1=mono,2=stereo) (default 2): ").strip() + channels = int(ch_input) if ch_input else 2 + + record_audio(record_duration, file_name, samplerate=samplerate, channels=channels, device=device) + except ValueError: + print("Invalid numeric input. Exiting.") + except Exception as e: + print("Error:", e) diff --git a/VOICE_RECORDER/voice_recorder.py b/VOICE_RECORDER/voice_recorder.py deleted file mode 100644 index 774cf663..00000000 --- a/VOICE_RECORDER/voice_recorder.py +++ /dev/null @@ -1,14 +0,0 @@ -import sounddevice as sd -import wavio - -def record_audio(duration, filename): - print("Recording...") - audio = sd.rec(int(duration * 44100), samplerate=44100, channels=2, dtype='int16') - sd.wait() # Wait until the recording is finished - wavio.write(filename, audio, 44100, sampwidth=2) # Save as WAV file - print(f"Recording saved as '{filename}'") - -if __name__ == "__main__": - record_duration = float(input("Enter duration in seconds: ")) - file_name = input("Enter filename (with .wav extension): ") - record_audio(record_duration, file_name) diff --git a/weather_cli.py b/weather_cli.py new file mode 100644 index 00000000..6949e990 --- /dev/null +++ b/weather_cli.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +""" +weather_cli.py +Simple Weather CLI using Open-Meteo and OpenStreetMap APIs. + +Usage: + python weather_cli.py "New Delhi" + python weather_cli.py "San Francisco" +""" + +import requests +import sys + +def get_coordinates(city): + """Get latitude and longitude for a city using Nominatim API.""" + url = "https://nominatim.openstreetmap.org/search" + params = {"q": city, "format": "json", "limit": 1} + resp = requests.get(url, params=params, headers={"User-Agent": "WeatherCLI/1.0"}) + resp.raise_for_status() + data = resp.json() + if not data: + raise ValueError(f"City '{city}' not found.") + return float(data[0]["lat"]), float(data[0]["lon"]) + +def get_weather(lat, lon): + """Fetch current weather from Open-Meteo API.""" + url = "https://api.open-meteo.com/v1/forecast" + params = { + "latitude": lat, + "longitude": lon, + "current_weather": True, + } + resp = requests.get(url, params=params) + resp.raise_for_status() + return resp.json()["current_weather"] + +def show_weather(city): + """Display weather info for a city.""" + try: + lat, lon = get_coordinates(city) + weather = get_weather(lat, lon) + print(f"🌍 Weather for {city}") + print(f"📍 Lat: {lat:.2f}, Lon: {lon:.2f}") + print(f"🌡️ Temperature: {weather['temperature']}°C") + print(f"💨 Windspeed: {weather['windspeed']} km/h") + print(f"🕒 Time: {weather['time']}") + except Exception as e: + print("Error:", e) + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Usage: python weather_cli.py ") + sys.exit(1) + city_name = " ".join(sys.argv[1:]) + show_weather(city_name)