while循环在脚本中意外退出

时间:2016-03-28 05:20:28

标签: python loops

两个月前开始学习Python,开启和关闭。还是初学者,但我来自坚实的C背景。我可能不会以“Python”的方式做事,因为C对我来说是如此根深蒂固,但我让我的脚本工作。但是,我刚刚添加了一个while循环,以便我可以多次运行它并退出用户请求。然而,无论输入是什么,while循环都会退出。我很确定我的缩进是正确的。这是整个脚本(删除了我的API密钥)。这是外部循环,完成时== 0:

#!/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()

1 个答案:

答案 0 :(得分:1)

第110行(if elif内的while waiting阻止)中存在错误。正确的陈述是:

if exit == 'x' or exit == 'X'

你的陈述是if exit == 'x' or 'X',这是不正确的。它将exitx进行比较,但不与X进行比较。你要写的是如果exit等于x或者exit等于X 但是你已经为编码,则exit等于x或X为True 。现在' X'始终为true,它与输入无关(因为您没有将它与任何变量进行比较),因此无论输入如何,循环都会退出。 elifelse阻止了同样的错误。

这与C

非常相似
相关问题