Skip to main content

Weather Forecast App in Python

Building a Weather Forecast App in Python

Building a Weather Forecast App in Python

Weather forecasting is an essential part of our daily lives, helping us plan our activities. In this article, we'll walk through the process of building a simple weather forecast app using Python. We’ll use the OpenWeatherMap API to get real-time weather data and display it in a user-friendly format.



Prerequisites

Before we start, make sure you have the following:

  • Python installed on your machine.
  • An API key from OpenWeatherMap (you can sign up for a free account to get one).
  • Flask or Tkinter (depending on whether you want a web-based or GUI-based app).

Step 1: Setting Up the Project

First, let's set up a basic Python project. Create a new directory for your project and navigate into it:

mkdir weather_app
cd weather_app

Next, create a new Python file named app.py where we will write our code:

touch app.py

Step 2: Installing Required Packages

We need to install some Python packages to work with APIs and handle HTTP requests. If you're using Flask, you'll also need to install it:

pip install requests Flask

Step 3: Writing the Python Code

In your app.py file, start by importing the necessary libraries:

import requests
from flask import Flask, render_template, request

Now, let's define the basic structure of our Flask app and set up a route to handle the weather data:

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    weather_data = None
    if request.method == 'POST':
        city = request.form.get('city')
        api_key = 'your_api_key_here'
        url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric'
        response = requests.get(url)
        weather_data = response.json()
    return render_template('index.html', weather=weather_data)

Step 4: Creating the HTML Template

Create an index.html file in a new directory named templates. This file will display the weather information:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather Forecast</title>
</head>
<body>
    <h1>Weather Forecast</h1>
    <form method="post">
        <input type="text" name="city" placeholder="Enter city name" required>
        <button type="submit">Get Weather</button>
    </form>

    {% if weather %}
    <h2>Weather in {{ weather['name'] }}</h2>
    <p>Temperature: {{ weather['main']['temp'] }}°C</p>
    <p>Description: {{ weather['weather'][0]['description'] }}</p>
    {% endif %}
</body>
</html>

Step 5: Running the App

Finally, run your Flask app by executing the following command in your terminal:

python app.py

Visit http://localhost:5000 in your browser, and you'll be able to see your weather forecast app in action!

Conclusion

In this article, we built a simple weather forecast app using Python and Flask. This project demonstrates how easy it is to interact with APIs in Python and create user-friendly web applications. You can extend this project by adding more features, such as a weather forecast for multiple days, or even integrating it into a larger project.

Comments

Popular posts from this blog

Functions in Python

Mastering Python Functions: A Comprehensive Guide Mastering Python Functions: A Comprehensive Guide Python functions are fundamental building blocks of Python programming. They allow you to encapsulate code into reusable pieces, making your programs more modular and easier to maintain. In this guide, we'll explore how to define and use functions in Python, including advanced topics such as lambda functions and decorators. Table of Contents: Defining Functions Function Arguments Returning Values Lambda Functions Decorators Scope and Lifetime Defining Functions In Python, functions are defined using the def keyword, followed by the function name and parentheses. The function body is indented and contains the code that will be executed when the function is called. Here's a basic exa...

Python Operators

Unlock the Power of Python Operators: A Complete Guide Unlock the Power of Python Operators: A Complete Guide Python operators are the backbone of any Python code, helping you perform a wide range of tasks—from basic arithmetic to more complex operations like bitwise manipulation. Whether you’re a novice or an experienced developer, understanding these operators is crucial to mastering Python. In this cheat sheet, we’ll break down all of Python’s operators, providing you with examples and explanations so you can use them confidently in your projects. Table of Contents: Arithmetic Operators Assignment Operators Comparison Operators Logical Operators Identity Operators Membership Operators Bitwise Operators Operator Precedence If you’re just s...

String Slicing in Python

Mastering String Slicing in Python: A Comprehensive Guide Mastering String Slicing in Python: A Comprehensive Guide Text data is ubiquitous in the world of programming and data analysis. Unlike numerical data, textual data often requires significant cleaning and manipulation. Textual data isn't limited to natural language text; it encompasses any sequence of characters, whether letters, numbers, symbols, or punctuation. In Python, this type of data is known as a string. Strings are incredibly versatile, and Python provides numerous tools to work with them. One of the most powerful techniques is string slicing, which allows you to extract specific portions of a string. What is String Slicing in Python? String slicing is the process of extracting a portion of a string, known as a substring. This is achieved by specifying the start and end positions of the slice, using the string’s index values. Understanding string slicing is esse...