2016-03-28 17 views
0

約2か月前にPythonを学び始めたばかりです。まだ初心者ですが、私は固体Cの背景から来ています。私はCがとても深く私に夢中になっているので、 "Python"のやり方ではないかもしれませんが、スクリプトを作っています。しかし、私はそれを複数回実行し、ユーザーの要求に応じて終了できるようにwhileループを追加しました。 whileループは入力に関係なく終了します。かなり私は私のインデントを正しいと確信しています。ここでは、私のAPIキーが削除された全体のスクリプトです。ループ中にループが予期せず終了する

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

のようなものです。追加のコンテキストを共有するためのリンクは歓迎されますが、唯一のリソースではありません。 (これはエディタの '{}'ボタンを使ってコードブロックとしてフォーマットできます) –

+0

これはたくさんのコードとみなされます。この問題を再現する最小限のコード**を投稿してください。 **こちら**をリンクしてください(リンクではありません)。 **問題がどこにあるかを正確に**示してください(あなたのコードで 'while'ループを検索するとは思わない)。 **あなたのデバッグ観測**を共有してください。 –

+0

あなたはwhileループのネストされた束を持っています、そして、バグがどこであるか推測するのは容易ではありません。 – ZdaR

答えて

1

線110(while waiting内部if elifブロック)でエラーがある:それはしばらくの間は== 0を終え、非常に外部ループです。正しい声明は:

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

if exit == 'x' or 'X'は正しくありません。 exitxと比較していますが、Xを比較していません。あなたが書いたいのは、出口がxに等しいか出口がXに等しい場合ですですが、のコードはexitがxに等しいかXがTrueであることを表します。今では 'X'は常に真であり、入力とは無関係です(変数と比較しないため)、入力に関係なくループが終了します。同じエラーがブロックelifとブロックelseにあります。

これはあなたのポスト内で直接コードの最も関連性の高い部分を含めてください非常にC

+0

ああ、私はそれを逃したと信じることはできません。 ありがとうございます! – Aurelius

+0

私はCの後でPythonを学び始めたときにも私と一緒に起こった。自由Pythonは、 'ifブロック'の括弧を必要としないことなど、それは初心者が間違いを犯すところです。私もしました – Sharad

関連する問題