Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
Python ✦ Beginner ⏱ 45 minutes

🌤️ Build a Weather App with Python

Build a real Python app that fetches live weather data from any city in the world. You'll learn to call APIs, parse JSON, and handle user input — three core skills used in almost every Python project.

🎯 What You'll Build

A command-line Python application where users type a city name and instantly see the current temperature, weather condition (clear, cloudy, rainy), humidity, and wind speed — pulled live from a free weather API.

📋 What You'll Need

By the end of this tutorial, you'll have a working weather app and you'll understand exactly how the web works behind the scenes. Let's get started.

1

Set up your project folder

Create a new folder for your project anywhere on your computer. Open it in VS Code. Inside, create a new file called weather.py — this is where all your code will live.

Open a terminal in VS Code (Ctrl + ` on Windows, Cmd + ` on Mac) and verify Python is installed:

python --version

You should see something like Python 3.11.0. If you get an error, install Python from python.org first.

2

Install the requests library

To talk to the weather API, we need a Python library called requests — the most popular tool for making HTTP requests. Install it with pip:

pip install requests

You'll see "Successfully installed requests" once it's done. This library lets your Python code fetch data from any website or API on the internet.

💡 Tip: If pip doesn't work, try pip3 or python -m pip install requests. These are common alternatives on different systems.
3

Get your free API key

Weather data comes from an API (Application Programming Interface) — a service that gives your program data on demand. We'll use OpenWeatherMap, which has a generous free tier.

  1. Go to openweathermap.org and click "Sign Up"
  2. Verify your email
  3. Go to your profile → "My API keys"
  4. Copy the default API key (it's a long string of letters and numbers)
⏱ Note: Newly created API keys take 10–15 minutes to activate. If you get an "invalid key" error later, wait a few minutes and try again.
4

Write the API request code

Open weather.py and start with this code. Paste your API key where it says YOUR_API_KEY_HERE.

weather.py
import requests

# Replace this with your actual API key
API_KEY = 'YOUR_API_KEY_HERE'
BASE_URL = 'https://api.openweathermap.org/data/2.5/weather'

# Ask the user for a city name
city = input('Enter city name: ')

# Build the request URL
url = f'{BASE_URL}?q={city}&appid={API_KEY}&units=metric'

# Send the request
response = requests.get(url)
data = response.json()

print(data)

Three things are happening: we ask the user for a city, build a URL pointing to the API, then requests.get() fetches the data and .json() converts it into a Python dictionary.

5

Run it and see the raw data

In your terminal, run:

python weather.py

Type a city like London and press Enter. You'll see a big block of JSON data:

Output
{'coord': {'lon': -0.1257, 'lat': 51.5085}, 'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}], 'main': {'temp': 18.5, 'humidity': 65}, 'wind': {'speed': 3.5}, ...}

This is the raw weather data. Now we just need to pull out the parts we care about and display them nicely.

6

Format the output nicely

Replace the last print(data) line with this — it extracts the useful information and displays it cleanly:

weather.py
# Extract the parts we want
temp = data['main']['temp']
condition = data['weather'][0]['main']
description = data['weather'][0]['description']
humidity = data['main']['humidity']
wind = data['wind']['speed']

# Display nicely
print('\n🌤️ Weather in ' + city.title() + '\n')
print(f'Temperature: {temp}°C')
print(f'Condition: {condition} ({description})')
print(f'Humidity: {humidity}%')
print(f'Wind Speed: {wind} m/s')

Save and run again. Type a city. You should see a clean, formatted weather report.

Output
🌤️ Weather in London

Temperature: 18.5°C
Condition: Clear (clear sky)
Humidity: 65%
Wind Speed: 3.5 m/s
7

Handle errors gracefully

What if the user types a city that doesn't exist? Or has no internet? Right now the program crashes. Let's fix that with a try/except block. Replace your entire code with this final version:

weather.py (final)
import requests

API_KEY = 'YOUR_API_KEY_HERE'
BASE_URL = 'https://api.openweathermap.org/data/2.5/weather'

city = input('Enter city name: ')
url = f'{BASE_URL}?q={city}&appid={API_KEY}&units=metric'

try:
    response = requests.get(url, timeout=5)
    data = response.json()

    if response.status_code != 200:
        print(f'❌ Error: {data["message"]}')
    else:
        temp = data['main']['temp']
        condition = data['weather'][0]['main']
        humidity = data['main']['humidity']
        wind = data['wind']['speed']

        print(f'\n🌤️ Weather in {city.title()}\n')
        print(f'Temperature: {temp}°C')
        print(f'Condition: {condition}')
        print(f'Humidity: {humidity}%')
        print(f'Wind Speed: {wind} m/s')

except requests.exceptions.RequestException:
    print('❌ Network error — check your internet connection.')

Now your app handles three real-world situations: invalid cities, network failures, and successful requests. That's the same pattern used in professional Python applications.

🎉

You did it!

You just built a real Python app that talks to the internet, parses live data, and handles errors gracefully — the same skills used in every modern Python project.

🚀 Take It Further

← All Tutorials

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.