|
| 1 | +# import required modules |
| 2 | +import requests, json |
| 3 | + |
| 4 | +# Enter your API key here |
| 5 | +api_key = "Your_API_Key" |
| 6 | + |
| 7 | +# base_url variable to store url |
| 8 | +base_url = "http://api.openweathermap.org/data/2.5/weather?" |
| 9 | + |
| 10 | +# Give city name |
| 11 | +city_name = input("Enter city name : ") |
| 12 | + |
| 13 | +# complete_url variable to store |
| 14 | +# complete url address |
| 15 | +complete_url = base_url + "appid=" + api_key + "&q=" + city_name |
| 16 | + |
| 17 | +# get method of requests module |
| 18 | +# return response object |
| 19 | +response = requests.get(complete_url) |
| 20 | + |
| 21 | +# json method of response object |
| 22 | +# convert json format data into |
| 23 | +# python format data |
| 24 | +x = response.json() |
| 25 | + |
| 26 | +# Now x contains list of nested dictionaries |
| 27 | +# Check the value of "cod" key is equal to |
| 28 | +# "404", means city is found otherwise, |
| 29 | +# city is not found |
| 30 | +if x["cod"] != "404": |
| 31 | + |
| 32 | + # store the value of "main" |
| 33 | + # key in variable y |
| 34 | + y = x["main"] |
| 35 | + |
| 36 | + # store the value corresponding |
| 37 | + # to the "temp" key of y |
| 38 | + current_temperature = y["temp"] |
| 39 | + |
| 40 | + # store the value corresponding |
| 41 | + # to the "pressure" key of y |
| 42 | + current_pressure = y["pressure"] |
| 43 | + |
| 44 | + # store the value corresponding |
| 45 | + # to the "humidity" key of y |
| 46 | + current_humidity = y["humidity"] |
| 47 | + |
| 48 | + # store the value of "weather" |
| 49 | + # key in variable z |
| 50 | + z = x["weather"] |
| 51 | + |
| 52 | + # store the value corresponding |
| 53 | + # to the "description" key at |
| 54 | + # the 0th index of z |
| 55 | + weather_description = z[0]["description"] |
| 56 | + |
| 57 | + # print following values |
| 58 | + print(" Temperature (in kelvin unit) = " + |
| 59 | + str(current_temperature) + |
| 60 | + "\n atmospheric pressure (in hPa unit) = " + |
| 61 | + str(current_pressure) + |
| 62 | + "\n humidity (in percentage) = " + |
| 63 | + str(current_humidity) + |
| 64 | + "\n description = " + |
| 65 | + str(weather_description)) |
| 66 | + |
| 67 | +else: |
| 68 | + print(" City Not Found ") |
0 commit comments