1

我在课堂上遇到异常问题。如果可能的话,我希望它返回到我的主脚本,或者任何可以避免我的程序崩溃的解决方案。我会给你看代码。

这是主要脚本:

from requestnew import requestNew


def chooseCountry():
    countryc = input("Enter which country your city is in(in english): ")
    rq.countrychoice.append(countryc)

def chooseCity():
    cityc = cityc = input("Enter the name of the city: ")
    rq.citychoice.append(cityc)

def makeForecast():
    try:
        for day in rq.data['forecast']['simpleforecast']['forecastday']:
            print ("Country: ", rq.countrychoice[-1], "City: ", rq.citychoice[-1])
            print (day['date']['weekday'] + ":")
            print ("Conditions: ", day['conditions'])
            print ("High: ", day['high']['celsius'] + "C", '\n' "Low: ", day['low']['celsius'] + "C", '\n')
    except Exception as e:
        print ("\nHave you typed in the correct country and city?\nBecause we got a" ,'"',e,'"', "error\nplease try again!")
        return menu


if __name__ == '__main__':
    """Introducion"""
    print ("\nThis program lets you see a weather forecast for your choosen city.")
    rq = requestNew()

    while True:
        try:
            print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
            menu = int(input("\nPress 1 for country\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n"))
            if menu == 1:
                chooseCountry()
            elif menu == 2:
                chooseCity()
            elif menu == 3:
                rq.forecastRequest()
                makeForecast()
            elif menu == 4:
                print ("\nThank you for using my application, farewell!")
                break
            elif menu >= 5:
                print ("\nYou pressed the wrong number, please try again!")
        except ValueError as e:
            print ("\nOps! We got a ValueError, info:", e, "\nplease try again!")
            continue 

这是我的课程代码:

import requests
import json

class requestNew:

    def __init__(self):
        self.countrychoice = []
        self.citychoice = []

    def countryChoice(self):
        self.countrychoice = []

    def cityChoice(self):
        self.citychoice = []

    def forecastRequest(self):
        try:
            r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + self.countrychoice[-1] + "/" + self.citychoice[-1] + ".json")
            self.data = r.json()
        except #?

正如您在上面看到的,我在def forecastRequest(self):. 问题是我不知道哪个异常以及如何正确返回它以避免任何程序崩溃。

如果您查看我的主脚本,您会发现我必须while True:从菜单中循环所有内容。

程序中的所有内容都正常工作,除非我按 3;elif menu == 3:没有选择国家def chooseCountry():或城市def chooseCity():。这是因为我在课堂上使用了一个列表,然后def forecastRequest(self):像这样打印它;countrychoice[-1]从输入中获取最后附加的列表项。当我在菜单中按 3 而不选择国家或城市时,列表将为空。

我的问题是,有没有办法让用户返回到我的主脚本中的菜单except #?def forecastRequest(self):或者当我尝试发出请求时,如果列表为空,是否有其他方法可以避免程序崩溃?

对不起我的英语,对不起,如果我的解释很混乱,我已经尽力让它尽可能容易理解。

4

1 回答 1

1

If you want control to return to the main loop, catch the exception in the main loop:

elif menu == 3:
    try:
        rq.forecastRequest()
    except IndexError:
        # self.countrychoice[-1] will raise an IndexError if self.countrychoice is empty
        # handle error
    else:
        makeForecast()                  
于 2013-11-15T10:59:20.163 回答