script to obtain temperature in a location in python

To obtain the temperature in a location using Python, you can use an API that provides such data. One popular API is OpenWeatherMap.

Here's an example script that uses the OpenWeatherMap API to obtain the current temperature in a given location, using the requests library to make the API request and JSON module to parse the response:

main.py
import requests
import json

# replace with your own API key
API_KEY = 'your_api_key_here'

# replace with the desired location
location = 'london'

# make the API request
response = requests.get(f'http://api.openweathermap.org/data/2.5/weather?q={location}&appid={API_KEY}&units=metric')

# parse the JSON response
data = json.loads(response.text)

# obtain the temperature
temperature = data['main']['temp']

print(f'The temperature in {location} is {temperature:.1f}°C')
474 chars
20 lines

Note that you'll need to sign up for a free API key from OpenWeatherMap to use this script. You can replace 'your_api_key_here' with your own API key in the code above. You'll also need to replace 'london' with the desired location. This script returns the temperature in Celsius by default, but you can change it to Fahrenheit by changing units=metric to units=imperial in the API request URL.

gistlibby LogSnag