[英]Calculating an average temperature using Python and weather API
我試圖通過查找平均日溫度在高和低之間的平均值,然后將平均時間范圍除以10,來計算10天的平均溫度。我使用的是天氣APi,在命令行上運行郵政編碼。 目前,我有無效的語法錯誤,但無法弄清楚出了什么問題-也許我缺少括號或使用了不正確的括號。 錯誤是:print city ['city'] ^ SyntaxError:語法無效
任何幫助,將不勝感激。
from weather import Weather
import sys
if len(sys.argv) > 1:
weather = Weather ()
location = weather.lookup_by_location((sys.argv[1]))
forecast = location.forecast()
city = location.location()
average = 0
for f in location.forecast():
averageTotal = f(f[int('high')] + f[int('low')] / 2
print city ['city']
print "10 day average temperature:" + str(averageTotal / 10)
else:
print "You must supply a postcode to get the atmospheric pressure."
歡迎使用python! 您的代碼可以通過諸如pylint
靜態代碼分析器進行pylint
。 嘗試使用它。 同樣,當您為for循環中的averageTotal
分配新值時,您正在計算的10天期間的平均值也會覆蓋自身。 這是一種更好的編寫方式。
import sys
from weather import Weather
if len(sys.argv) > 1:
weather = Weather()
location = weather.lookup_by_location((sys.argv[1]))
forecast = location.forecast()
city = location.location()
average = 0
print city['city']
averageTotal = 0
for f in location.forecast():
averageTotal += (int(f['high']) + int(f['low']))
print "10 day average temperature:" + str(averageTotal / 10)
PS如果您不熟悉python,請不要使用for-else
。 這只會使您感到困惑。 如果您想閱讀它的用途,請參考此內容 。
好吧,您的錯誤告訴您, print city ['city']
是無效的,它是非常明確的。
您是否要在字典city
打印關鍵'city'
的價值? 然后,您需要刪除['city']
之前的空白。
否則,這條線實際上應該做什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.