2

我已经调用了这个方法,但是当数据返回时,它在数据下方返回一个 None 。我该如何防止呢?

def weather_Connection(interval,apikey):


    print print_forecast('Choa Chu Kang',get_response('/forecast/apikey/1.394557,103.746396'))
    print print_forecast('Yishun',get_response('/forecast/apikey/1.429463,103.84022'))
    print print_forecast('Redhill',get_response('/forecast/apikey/1.289732,103.81675'))
    print print_forecast('Jalan Besar',get_response('/forecast/apikey/1.312426,103.854317'))
    print print_forecast('Jurong West',get_response('/forecast/apikey/1.352008,103.698599'))
    print print_forecast('Tampines',get_response('/forecast/apikey/1.353092,103.945229')) 

数据以这种方式返回

cloudCover : 0.75
dewPoint: 24.87
humidity: 80.00
icon : partly-cloudy-night
ozone : 276.67
precipIntensity : 0
precipProbability : 0
pressure : 1009.61
summary : Dry and Mostly Cloudy
temperature: 28.56
visibility : 6.21
windBearing : 127
windSpeed : 4.57
psiAverage : 20
latitude : 1.394557
longitude : 103.746396
location : Choa Chu Kang
None
4

2 回答 2

6

您正在打印函数的返回值,在函数内部打印。删除print您用于打印调用返回值的语句。

你在哪里做:

print weather_Connection(interval, api_key)

删除print

weather_Connection(interval, api_key)

Python 中的函数总是有返回值,即使你不使用return语句,默认为None

>>> def foo(): pass  # noop function
... 
>>> print foo()
None

另一种方法是不在您的函数中使用print,而是返回一个字符串:

def weather_Connection(interval,apikey):
    result = [
        print_forecast('Choa Chu Kang',get_response('/forecast/apikey/1.394557,103.746396')),
        print_forecast('Yishun',get_response('/forecast/apikey/1.429463,103.84022')),
        print_forecast('Redhill',get_response('/forecast/apikey/1.289732,103.81675')),
        print_forecast('Jalan Besar',get_response('/forecast/apikey/1.312426,103.854317')),
        print_forecast('Jurong West',get_response('/forecast/apikey/1.352008,103.698599')),
        print_forecast('Tampines',get_response('/forecast/apikey/1.353092,103.945229')),
    ]
    return '\n'.join(result)
于 2013-07-07T16:47:58.880 回答
1

删除print()调用,函数正在返回None

函数的默认返回值None在 python 中。print()如果您在函数内部打印并且没有从中返回任何内容,那么在调用该函数时就不需要了。

演示:

>>> def func():
...     print ("foo")
...     
>>> print(func())
foo
None
>>> func()      #works fine without `print()`
foo
于 2013-07-07T16:47:55.037 回答