0

我正在编写的当前程序有一些问题。

我让用户输入一个国家,然后输入那个国家的城市,然后使用 API 查看所选城市的天气预报。

我正在使用一个类,如下所示:

class requestChoice:

    def __init__(self):
        self.countrychoice = None
        self.citychoice = None

    def countryChoice(self):
        self.countrychoice = input("Enter which country your city is in(in english): ")

    def cityChoice(self):
        self.citychoice = input("Enter the name of the city: ")

我的主程序如下所示:

from requestchoice import requestChoice

import requests

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

rc = requestChoice()
while True:
    print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
    menu = input("\nPress 1 for contry\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n")
    if menu == "1":
        rc.countryChoice()
    elif menu == "2":
        rc.cityChoice()
    elif menu == "3":
        r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
        data = r.json()
        try:
            for day in data['forecast']['simpleforecast']['forecastday']:
                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")
    else: 
        print ("\nGoodbye")
        break

当我运行我的程序时,我得到了错误NameError: name 'countrychoice' is not defined。这将是相同的错误citychoice。我尝试在我的班级中创建一个列表并将其附加countrychoice到列表中,但没有任何运气。我应该如何让它如愿工作?

4

3 回答 3

1

您必须使用相应的对象名称访问它们。在这种情况下

rc.countrychoice
rc.citychoice

所以,这条线

r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")

变成

r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + rc.countrychoice + "/" + rc.citychoice + ".json")
于 2013-11-13T12:27:18.580 回答
1

你需要在这里使用rc.countrychoicerc.citychoice

    r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + rc.countrychoice + "/" + rc.citychoice + ".json")
于 2013-11-13T12:29:48.497 回答
1

你在这里得到一个NameError

r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")

因为你没有名字countrychoicecitychoice定义。也许您打算使用rc.countrychoiceandrc.citychoice代替?

于 2013-11-13T12:30:23.440 回答