Skip to content
This repository was archived by the owner on Apr 24, 2025. It is now read-only.

Commit dccb69f

Browse files
committed
feat: user can choose to output temperature either in Celsius or Fahrenheit.
1 parent 81924ba commit dccb69f

File tree

2 files changed

+48
-14
lines changed

2 files changed

+48
-14
lines changed

projects/API Based Weather Report/API Based Weather Report.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import requests
22
from datetime import datetime
3-
from Util_Functions import wind_degree_to_direction, unix_timestamp_to_localtime
3+
from Util_Functions import wind_degree_to_direction, unix_timestamp_to_localtime, convert_temperature
44

55

66
# Function to fetch weather data from OpenWeatherMap API
@@ -25,7 +25,7 @@ def fetch_weather(api_key, location):
2525

2626

2727
# Function to write weather information to a text file
28-
def write_to_file(weather_data):
28+
def write_to_file(weather_data, temperature_unit):
2929
try:
3030
# Opening the file "weatherinfo.txt" in write mode
3131
with open("weatherinfo.txt", "w+") as f:
@@ -35,15 +35,16 @@ def write_to_file(weather_data):
3535
# Writing header information to the file
3636
if "name" in weather_data and "sys" in weather_data and "country" in weather_data["sys"]:
3737
f.write("-------------------------------------------------------------\n")
38-
f.write(f"Weather Stats for - {weather_data['name']} | {weather_data['sys']['country']} | {date_time}\n")
38+
f.write(f"Weather Stats for - {weather_data['name']} | {weather_data['sys']['country']} "
39+
f"| {date_time}\n")
3940
f.write("-------------------------------------------------------------\n")
4041

4142
# Writing temperature information to the file
4243
if "main" in weather_data and "temp" in weather_data["main"]:
4344
f.write(
44-
"\tCurrent temperature is : {:.2f} °C\n".format(
45-
weather_data["main"]["temp"] - 273.15
46-
)
45+
"\tCurrent temperature is : "
46+
+ convert_temperature(weather_data["main"]["temp"], temperature_unit)
47+
+ "\n"
4748
)
4849

4950
# Writing weather description information to the file
@@ -105,9 +106,14 @@ def main():
105106
"You can obtain your API key by signing up at https://home.openweathermap.org/users/sign_up"
106107
)
107108

108-
# Prompting the user to input API key and city name
109+
# Prompting the user to input API key, city name, and
109110
api_key = input("Please enter your OpenWeatherMap API key: ")
110111
location = input("Enter the city name: ")
112+
temperature_unit = input("Enter the temperature unit. 'C' for Celsius and 'F' for Fahrenheit: ")
113+
114+
if not (temperature_unit.upper() == "C" or temperature_unit.upper() == "F"):
115+
print("Temperature unit must either be 'C' or be 'F'.")
116+
return
111117

112118
# Fetching weather data using the provided API key and location
113119
weather_data = fetch_weather(api_key, location)
@@ -123,15 +129,14 @@ def main():
123129
return
124130

125131
# Writing weather information to file
126-
write_to_file(weather_data)
132+
write_to_file(weather_data, temperature_unit)
127133

128134
# Printing weather information to console
129135
print("Current City : " + weather_data['name'] + ', ' +
130136
weather_data['sys']['country'])
131137
print(
132-
"Current temperature is: {:.2f} °C".format(
133-
weather_data["main"]["temp"] - 273.15
134-
)
138+
"Current temperature is: "
139+
+ convert_temperature(weather_data["main"]["temp"], temperature_unit)
135140
)
136141
print("Current weather desc : " + weather_data["weather"][0]["description"])
137142
print("Current Humidity :", weather_data["main"]["humidity"], "%")

projects/API Based Weather Report/Util_Functions.py

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def wind_degree_to_direction(str_wind_degree):
1212
try:
1313
wind_degree = int(str_wind_degree)
1414
except ValueError:
15-
return "API Wind Degree data error!"
15+
return "API Wind Degree data format error!"
1616

1717
directions = [
1818
"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
@@ -34,12 +34,12 @@ def unix_timestamp_to_localtime(str_unix_timestamp, str_timezone_offset_seconds)
3434
try:
3535
unix_timestamp = int(str_unix_timestamp)
3636
except ValueError:
37-
return "API sunset/sunrise data error!"
37+
return "API sunset/sunrise data format error!"
3838

3939
try:
4040
timezone_offset_seconds = int(str_timezone_offset_seconds)
4141
except ValueError:
42-
return "API timezone data error!"
42+
return "API timezone data format error!"
4343

4444
# Convert Unix timestamp to UTC datetime
4545
utc_time = datetime.utcfromtimestamp(unix_timestamp)
@@ -48,3 +48,32 @@ def unix_timestamp_to_localtime(str_unix_timestamp, str_timezone_offset_seconds)
4848
local_time = utc_time + timedelta(seconds=timezone_offset_seconds)
4949

5050
return local_time.strftime('%Y-%m-%d %H:%M:%S')
51+
52+
53+
def convert_temperature(str_temperature_kelvin, temperature_unit):
54+
"""
55+
Convert temperature in Kelvin degree to Celsius degree or Fahrenheit degree based on second parameter .
56+
57+
:param str_temperature_kelvin: str, temperature in Kelvin degree (e.g., "291.19")
58+
:param temperature_unit: str, "C" for Celsius, "F" for Fahrenheit
59+
:return: temperature (e.g., "21.07 °C" or "67.12 °F")
60+
"""
61+
# Convert strings to integers
62+
try:
63+
temperature_k = int(str_temperature_kelvin)
64+
except ValueError:
65+
return "API temperature data format error!"
66+
67+
# Validate temperature_unit
68+
unit = str(temperature_unit).upper()
69+
if not (unit == "C" or unit == "F"):
70+
return "Temperature unit must either be 'C' or be 'F'!"
71+
72+
# Converting
73+
if unit == 'C':
74+
temperature_c = temperature_k - 273.15
75+
return f"{temperature_c:.2f} °C"
76+
77+
if unit == 'F':
78+
temperature_f = temperature_k * 9 / 5 - 459.67
79+
return f"{temperature_f:.2f} °F"

0 commit comments

Comments
 (0)