DEV Community

Diamantino Almeida
Diamantino Almeida

Posted on

2

☀️ Get the Weather: A Fun and Easy Python Script! 🌧️

Ever wondered if you should grab your sunglasses or an umbrella before heading out?

Well, say goodbye to those weather-related dilemmas!

With a tiny Python script, you can fetch the weather conditions right from your area. Ready to become a weather wizard?

Let’s dive in!

🌟 What You’ll Need:

**Python Installed:** Make sure you have Python on your machine. If you don’t, download it from python.org.
API Key: Sign up for a free API key at OpenWeatherMap. This magical key will unlock the weather data for you!
Enter fullscreen mode Exit fullscreen mode

🛠️ Step-by-Step Guide:

  1. Install the Requests Library:

First things first, we need a special tool to help us make requests. Open your terminal and type this:

bash

pip install requests

2. Write the Script:

Now, let’s whip up our weather script! Open your favourite code editor (Visual Studio Code, PyCharm, or even Notepad will do) and create a new file named weather.py. Here’s the code you need to copy-paste:

python

`import requests

Replace 'YOUR_API_KEY' with your actual API key

API_KEY = 'YOUR_API_KEY'
CITY = 'your_city_name' # e.g., 'London'
URL = f'http://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}&units=metric'

response = requests.get(URL)
data = response.json()

if response.status_code == 200:
main = data['main']
weather = data['weather'][0]
temperature = main['temp']
humidity = main['humidity']
weather_description = weather['description']

print(f'Temperature: {temperature}°C')
print(f'Humidity: {humidity}%')
print(f'Weather: {weather_description.capitalize()}')
Enter fullscreen mode Exit fullscreen mode

else:
print('City not found. Please check your city name.')`

  1. Run the Script:

Alright, you’re almost there! Save your file and head back to your terminal. Run your script with the following command:

bash

python weather.py

🎉 Voilà! You’re All Set!

Just like that, you can now see the current weather conditions right in your terminal! 🌈 If it’s too hot, grab a cold drink; if it’s raining, don’t forget your umbrella!
🧑‍🎤 Get Creative!

Feel free to tinker with the script—change the city name or add new features like weather forecasts or alerts. The sky’s the limit!
🌈 Happy Coding!

Now go on, and become the weather guru among your friends! You’ve got this! 💪

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay