如何在函数的return print语句末尾删除“ None”?

时间:2019-10-30 04:32:46

标签: python function class

有人可以解释为什么在函数return语句的末尾以及为什么我会收到“无”,以及如何将其删除吗?我没有看到打印语句如何以任何方式触发它。

class City:
    # Task 1
    def __init__ (self, name, label, lat, lon, pop_dict):
        self.name = name
        self.label = label
        self.lat = lat
        self.lon = lon
        self.pop_dict = pop_dict
    def printPopChange(self, year1, year2): 
        pop_dict = self.pop_dict #pop_dict[year1]
        year1pop = pop_dict[year1]
        year2pop = pop_dict[year2]
        popchange = float(year2pop) - float(year1pop)
        print "The population difference in", self.name, "from", year1.strip("yr"), "to", year2.strip("yr"), "is", popchange, "million people."
Cities = []

f = open("CityPop.csv","r")
header = f.readline()
header = header.strip().split(",")
for line in f:
    record = line.strip().split(",")
    pop = {}
    for i in range (5, 14):
        pop[header[i]] = record[i]
    newCity = City(name = record[3], label = record[4], lat = record[1], lon = record[2], pop_dict = pop)
    Cities.append(newCity)

例如,如果我运行: print Cities[0].printPopChange("yr1990", "yr1995")

我收到: "The population difference in Tokyo from 1990 to 1995 is 1.06 million people." “无”`

2 个答案:

答案 0 :(得分:1)

printPropChange()打印消息本身,不返回任何内容。只需不使用print即可调用该函数。

Cities[0].printPopChange("yr1990", "yr1995")

答案 1 :(得分:0)

在函数末尾用print替换return

然后将返回的元组的所有元素都连接成字符串:

print ''.join(Cities[0].printPopChange("yr1990", "yr1995"))