Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions Number_Guessing/Number-guesser/Number_guesser.py
Original file line number Diff line number Diff line change
@@ -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()
1 change: 1 addition & 0 deletions Number_Guessing/Number-guesser/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Simple CLI game: guess a random number (1–100), get feedback (too high/low), type `q` to quit.
58 changes: 58 additions & 0 deletions VOICE_RECORDER/Simple _interactive_audio_recorder.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 0 additions & 14 deletions VOICE_RECORDER/voice_recorder.py

This file was deleted.

55 changes: 55 additions & 0 deletions weather_cli.py
Original file line number Diff line number Diff line change
@@ -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 <city name>")
sys.exit(1)
city_name = " ".join(sys.argv[1:])
show_weather(city_name)