0

Just started learning Python about two months ago, on and off. Still a beginner, but I come from a solid C background. I might not do things the "Python" way, as C is so heavily ingrained into me, but I got my script working. However, I just added a while loop so that I can run it multiple times and exit on user request. The while loop just exits no matter what the input, though. Pretty sure I have my indentation correct. Here's the whole script (with my API key removed). It's the very outside loop, the while finished == 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()
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Aurelius
  • 414
  • 4
  • 16
  • Please include the most relevant portions of code directly within your post. A link is welcome for sharing additional context, but not as the only resource. (It can be formatted as a code block using the `{}` button in the editor.) – Jonathan Lonowski Mar 28 '16 at 05:23
  • This is considered tons of code. Please post **a minimal piece of code** which reproduces the problem. Please post it **here** (and not in a link). Please indicate **exactly** where the problem is (don't expect us to search some `while` loop in your code). Please share **your debug observations**. – barak manos Mar 28 '16 at 05:24
  • You have a nested bunch of while loops, and it is not easy to guess where the bug is .. – ZdaR Mar 28 '16 at 05:25
  • Related: [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – Jonathan Lonowski Mar 28 '16 at 05:27
  • As I said the formatted wasn't working. Was messing everything up. Then the other guy mentioned too much code -- but I didn't know where the bug was, hence why I included the whole code. And to the third comment, it ended up being, basically, a syntax error. – Aurelius Mar 28 '16 at 06:07
  • Also regarding the nested while loops comment -- one of the many reasons I like C syntax and IDEs -- much easier to actually see the blocks, at least IMO. I find it hard because I'm not used to the Python syntax yet. I like that in other IDEs it actually highlights the block you're in. – Aurelius Mar 28 '16 at 06:11

1 Answers1

1

There is an error in line 110 (if elif block inside while waiting). Correct statement would be:

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

your statement reads if exit == 'x' or 'X' which is incorrect. It is comparing exit to x but not to X. What you want to write is if exit is equal to x or exit is equal to X but you have coded for either exit is equal to x or X is True. Now 'X' is always true and it is independent of your input (because you are not comparing it to any variable) and hence the loop exits irrespective of input. Same mistake is there in elif and else block.

This is very much like C

Sharad
  • 1,867
  • 14
  • 33
  • It happened with me as well when I started learning Python after C. The liberty Python provides such as not needing the brackets in the `if blocks` makes us assume more. That's where beginners commit mistakes. I did too – Sharad Mar 28 '16 at 06:10