Reputation: 1
I am just learning python and I am wondering if there is a better way to extract the most current temperature from the res variable.
from noaa_sdk import noaa
from datetime import datetime
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
n = noaa.NOAA()
res = n.get_observations('25311', 'US', start=date, end=None, num_of_stations=1)
temp= (next(res))
value =(temp.get('temperature'))
temperature = (value['value'])
temperature = temperature*9/5+32
print(temperature, ' F')
Upvotes: 0
Views: 82
Reputation: 15300
The example docs for the noaa_sdk
package make heavy use of loops. I would suggest, if you're just learning Python, that you try to use a loop-oriented style.
from datetime import datetime
from noaa_sdk import noaa
def to_freedom_degrees(temp_c):
return 32.0 + 9.0 / 5.0 * temp_c
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
observations = noaa.NOAA().get_observations('25311', 'US', start=date, end=None, num_of_stations=1)
for observation in observations:
temp_c = observation['temperature']
temp_f = to_freedom_degrees(temp_c)
print(temperature, ' F')
# I only want one temperature
break
else:
print('No temperature found!')
Upvotes: 0
Reputation: 49784
Your code is reasonably efficient, but it could be trimmed down to:
from noaa_sdk import noaa
import datetime as dt
date = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
res = noaa.NOAA().get_observations('25311', 'US', start=date)
print('{:.1f} F'.format( next(res)['temperature']['value'] * 9 / 5 + 32))
44.1 F
Upvotes: 2
Reputation: 11
If you meant computational efficiency, there is not much room to improve it.
If you meant shorter lines of code, temp= (next(res))
part, which has anything to do with extracting data in your code, seems already very short.
Upvotes: 0