komut dosyasında beklenmedik bir şekilde çıkarken Python'u yaklaşık iki ay önce, açıp kapamaya başladım. Hala yeni başlayan, ama ben sağlam bir C arka plandan geliyorum. C, bana çok ağır bir şekilde gömülü olduğu için, "Python" tarzında bir şey yapamayabilirim, ama senaryolarımı çalıştırdım. Ancak, bir süre döngü ekledim, böylece birden çok kez çalıştırabilir ve kullanıcı isteğinden çıkabilirim. While döngüsü ne olursa olsun girişten çıkar. Eminim girintim doğru. İşte bütün script (API anahtarım kaldırılmış).Döngüler
#!/usr/bin/env python3
import sys
import requests
import json
import time
appid = {'key': 'xxxxxxxxxxxxxxx'}
kingston = {'city': "/Canada/Kingston.json", 'city_str': "Kingston, Ontario"}
ottawa = {'city': "/Canada/Ottawa.json", 'city_str': "Ottawa, Ontario"}
toronto = {'city': "/Canada/Toronto.json", 'city_str': "Toronto, Ontario"}
vancouver = {'city': "/Canada/Vancouver.json", 'city_str': "Vancouver, British Columbia"}
sydney = {'city': "/Australia/Sydney.json", 'city_str': "Sydney, Australia"}
wellington = {'city': "/zmw:00000.1.93436.json", 'city_str': "Wellington, New Zealand"}
london = {'city': "/zmw:00000.1.03772.json", 'city_str': "London, UK"}
bergen = {'city': "/zmw:00000.1.01317.json", 'city_str': "Bergen, Norway"}
def cityquery(query):
searchresult = requests.get("http://autocomplete.wunderground.com/aq", params={'query': query})
results = json.loads(searchresult.text)
for index, x in enumerate(results['RESULTS'], start=1):
print(index, x['name'])
selection = input("Please select a number from the list:")
return {'city': results['RESULTS'][int(selection) - 1]['l'] + ".json", 'city_str': results['RESULTS'][int(selection) - 1]['name']}
def getWeather():
finished = 0
while finished == 0:
selected = 0
print("Please choose a city, or enter s to search by city name:")
print("\t1)", toronto['city_str'])
print("\t2)", sydney['city_str'])
print("\t3)", london['city_str'])
print("\t4)", vancouver['city_str'])
print("\t5)", ottawa['city_str'])
print("\t6)", kingston['city_str'])
print("\t7)", wellington['city_str'])
print("\t8)", bergen['city_str'])
while selected == 0:
citynumber = input("Enter a city number or s: ")
if citynumber == '1':
current_city = toronto
selected = 1
elif citynumber == '2':
current_city = sydney
selected = 1
elif citynumber == '3':
current_city = london
selected = 1
elif citynumber == '4':
current_city = vancouver
selected = 1
elif citynumber == '5':
current_city = ottawa
selected = 1
elif citynumber == '6':
current_city = kingston
selected = 1
elif citynumber == '7':
current_city = wellington
selected = 1
elif citynumber == '8':
current_city = bergen
selected = 1
elif citynumber == 's':
searchterm = input("Please type the first few characters of a city name: ")
current_city = cityquery(searchterm)
selected = 1
else:
print("Invalid entry!")
current_time = time.localtime()
print("The current time is", str('{:02d}'.format(current_time[3])) + ":" + str('{:02d}'.format(current_time[4])) + ":" + str('{:02d}'.format(current_time[5])))
print("Forecast for", current_city['city_str'])
#Current conditions
print("Getting current conditions...")
page = requests.get("http://api.wunderground.com/api/" + str(appid['key']) + "/conditions/q/" + current_city['city'])
values = json.loads(page.text)
# DEBUG print(page.text)
# DEBUG print(current_city)
temp = float(values['current_observation']['temp_c'])
if values['current_observation']['windchill_c'] == 'NA':
temp_wc = temp
else:
temp_wc = float(values['current_observation']['windchill_c'])
print("The temperature in", current_city['city_str'], "is currently", str('{:.2f}'.format(temp)) + "C feeling like", str('{:.2f}'.format(temp_wc)) + "C")
pressure_in = float(values['current_observation']['pressure_in'])
pressure_kp = float(values['current_observation']['pressure_mb'])/10.0
print("The barometric pressure is", str('{:.2f}'.format(pressure_in)), "inches of mercury or", str('{:.1f}'.format(pressure_kp)), "kilopascals.")
wind_speed = float(values['current_observation']['wind_kph'])
wind_gust = float(values['current_observation']['wind_gust_kph'])
wind_dir = str(values['current_observation']['wind_dir'])
if wind_gust == 0:
print("The wind is", str('{:.2f}'.format(wind_speed)), "km/h from the", wind_dir)
else:
print("The wind is", str('{:.2f}'.format(wind_speed)), "km/h, gusting to", str('{:.2f}'.format(wind_gust)), "km/h from the", wind_dir)
#Forecast
print("Getting forecast...")
page = requests.get("http://api.wunderground.com/api/" + str(appid['key']) + "/forecast/q" + current_city['city'])
values = json.loads(page.text)
for x in [0, 1, 2, 3, 4, 5]:
print("Forecast for", values['forecast']['txt_forecast']['forecastday'][x]['title'], ":", values['forecast']['txt_forecast']['forecastday'][x]['fcttext_metric'])
waiting = 0 # loop until valid input
while waiting == 0:
exit = input("Press x to exit or c to check again...")
if exit == 'x' or 'X':
finished = 1
waiting = 1
elif exit == 'c' or 'C':
finished = 0
waiting = 1
else:
finished = 0
waiting = 0
if __name__ == "__main__":
getWeather()
doğrudan Yazınızın içinde kodun en alakalı kısımlarını da ekleyin çok benzer. Ek bağlamı paylaşmak için bir bağlantı açığa çıkar, ancak tek kaynak olarak değil. (Editördeki '{}' düğmesini kullanarak bir kod bloğu olarak biçimlendirilebilir.) –
Bu, tonlarca kod olarak kabul edilir. Lütfen problemi yeniden üreten ** en az bir kod ** gönderin. Lütfen buraya ** yazınız (ve bir bağlantıda değil). Lütfen problemin tam olarak ** olduğunu ** belirtin (kodunuzda bazı 'while' döngüsünü aramamızı beklemeyin). Lütfen hata ayıklama gözlemlerinizi ** paylaşın. –
Döngüleri yaparken yuvalanmış bir demetiniz var ve hatanın nerede olduğunu tahmin etmek kolay değil .. – ZdaR