Ich habe gerade angefangen, Python vor zwei Monaten zu lernen. Noch ein Anfänger, aber ich komme aus einem soliden C-Hintergrund. Ich mache vielleicht keine Dinge auf "Python" Weise, da C so stark in mir verwurzelt ist, aber ich habe mein Skript funktioniert. Allerdings habe ich gerade eine while-Schleife hinzugefügt, so dass ich es mehrmals ausführen und auf Benutzeranforderung beenden kann. Die while-Schleife wird jedoch unabhängig von der Eingabe beendet. Ziemlich sicher, dass meine Einrückung korrekt ist. Hier ist das ganze Skript (mit meinem API-Schlüssel entfernt). Es ist die sehr außerhalb Schleife, die während beendet == 0:While-Schleifen werden im Skript unerwartet beendet.
#!/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()
enthalten Bitte beachten Sie die wichtigsten Teile des Codes direkt in Ihrem Beitrag. Ein Link ist zum Freigeben zusätzlichen Kontextes willkommen, aber nicht als einzige Ressource. (Es kann als ein Code-Block mit dem '{}' Knopf im Editor formatiert werden.) –
Dies wird Tonnen von Code betrachtet. Bitte post ** ein minimales Stück Code **, das das Problem reproduziert. Bitte poste es ** hier ** (und nicht in einem Link). Bitte geben Sie ** genau an, wo das Problem liegt (erwarten Sie nicht, dass wir eine "while" -Schleife in Ihrem Code suchen). Bitte teile ** deine Debug-Beobachtungen **. –
Sie haben eine verschachtelte Menge von while-Schleifen, und es ist nicht einfach zu erraten, wo der Fehler liegt. – ZdaR