Ready to build your first real Python project? This tutorial will guide you through creating a weather application that fetches real weather data and displays it beautifully in the terminal.
What You'll Learn
- Making HTTP requests with the
requestslibrary - Working with JSON data from APIs
- Error handling and user input
- Formatting terminal output
Step 1: Project Setup
# Create project folder
mkdir weather-app && cd weather-app
# Create virtual environment
python -m venv venv
source venv/bin/activate # Mac/Linux
# venv\Scripts\activate # Windows
# Install dependencies
pip install requestsStep 2: The Main Code
import requests
import sys
def get_weather(city):
"""Fetch weather data for a city."""
# Using wttr.in - a free weather API (no key needed!)
url = f"https://wttr.in/{city}?format=j1"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Error fetching weather: {e}")
return None
def display_weather(data, city):
"""Display weather information in a nice format."""
current = data["current_condition"][0]
temp_c = current["temp_C"]
temp_f = current["temp_F"]
humidity = current["humidity"]
description = current["weatherDesc"][0]["value"]
wind_speed = current["windspeedKmph"]
feels_like = current["FeelsLikeC"]
print(f"""
Weather for {city.title()}
{"=" * 35}
Description: {description}
Temperature: {temp_c}C / {temp_f}F
Feels Like: {feels_like}C
Humidity: {humidity}%
Wind Speed: {wind_speed} km/h
{"=" * 35}
""")
def main():
print("Python Weather App")
print("-" * 20)
while True:
city = input("Enter city name (or 'quit' to exit): ").strip()
if city.lower() == "quit":
print("Goodbye!")
break
if not city:
print("Please enter a valid city name.")
continue
print(f"Fetching weather for {city}...")
data = get_weather(city)
if data:
display_weather(data, city)
else:
print("Could not retrieve weather data.")
if __name__ == "__main__":
main()Step 3: Running the App
python weather.pySample Output
Python Weather App
--------------------
Enter city name (or 'quit' to exit): London
Fetching weather for London...
Weather for London
===================================
Description: Partly cloudy
Temperature: 18C / 64F
Feels Like: 17C
Humidity: 65%
Wind Speed: 15 km/h
===================================Bonus: Add a 3-Day Forecast
def display_forecast(data):
"""Show 3-day forecast."""
print(" 3-Day Forecast:")
for day in data["weather"][:3]:
date = day["date"]
max_temp = day["maxtempC"]
min_temp = day["mintempC"]
desc = day["hourly"][4]["weatherDesc"][0]["value"]
print(f" {date}: {desc}, {min_temp}-{max_temp}C")What's Next?
Once you have this working, try these enhancements:
- Add colored output with the
coloramalibrary - Save favorite cities to a file
- Build a GUI version with
tkinter - Add weather alerts and notifications
No comments yet. Be the first!