
私
ChatGPTさん、簡単な天気予報アプリをつくってみてください!
Pythonで書かれた簡易天気予報アプリです。このアプリはOpenWeatherMap APIを使用して、ユーザーが指定した都市の天気情報を取得して表示します。具体的には、以下の機能があります:
- 都市名の入力: ユーザーは任意の都市名を入力します。
- 天気情報の取得: 入力された都市名に基づいて、OpenWeatherMap APIから天気情報を取得します。
- 天気情報の表示:
- 天気の概要: その都市の現在の天気状態(晴れ、曇り、雨など)を表す短い説明。
- 気温: 現在の気温(摂氏)。
- 湿度: 現在の湿度の割合(パーセント)。
- 風速: 現在の風速(メートル毎秒)。
このアプリはコンソールベースで動作し、Pythonの requests
ライブラリを使用してAPIへのリクエストを行います。OpenWeatherMapのAPIキーが必要で、あらかじめ取得してコードに組み込む必要があります。
import requests
def get_weather(city, api_key):
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 data.get("cod") != 200:
print("City not found.")
return
weather = data['weather'][0]['description']
temperature = data['main']['temp']
humidity = data['main']['humidity']
wind_speed = data['wind']['speed']
print(f"Weather in {city}:")
print(f" Description: {weather}")
print(f" Temperature: {temperature}°C")
print(f" Humidity: {humidity}%")
print(f" Wind Speed: {wind_speed} m/s")
def main():
api_key = 'YOUR_API_KEY' # ここにあなたのOpenWeatherMap APIキーを入力してください。
city = input("Enter a city name: ")
get_weather(city, api_key)
if name == "main":
main()