python-3.x 为什么try正在工作时,它从异常返回false

k7fdbhmy  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(113)
allAirports = []
allFlights = {}

def loadData(airportFile, flightFile):

    try:
        airFile = open(airportFile, "r")
        fileFlight = open(flightFile, "r")

        while True:

            line = airFile.readline()
            line = line.replace(' ', '')
            line = line.replace('  ', '')
            airList = list(line.split(','))
            airList[-1] = airList[-1].strip()

            if airList[0] == '':
                line1 = fileFlight.readline()
                line1 = line1.replace(' ', '')
                line1 = line1.replace('  ', '')
                line1 = line1.replace('    ', '')
                flightList = list(line1.split(','))
                flightList[-1] = flightList[-1].strip()

                for i in range (1):

                    line2 = getAirportByCode(flightList[1])
                    line2 = line2.replace('(', ' ')
                    line2 = line2.replace(')', ' ')
                    line2 = line2.replace(',', ' ')
                    line2 = line2.split()
                    line2[1] = re.sub(r"([A-Z])", r" \1", line2[1]).lstrip()
                    line2[2] = re.sub(r"([A-Z])", r" \1", line2[2]).lstrip()

                    line3 = getAirportByCode(flightList[2])
                    line3 = line3.replace('(', ' ')
                    line3 = line3.replace(')', ' ')
                    line3 = line3.replace(',', ' ')
                    line3 = line3.split()
                    line3[1] = re.sub(r"([A-Z])", r" \1", line3[1]).lstrip()
                    line3[2] = re.sub(r"([A-Z])", r" \1", line3[2]).lstrip()

                    if flightList[1] in allFlights:
                        allFlights[flightList[1]] += [Flight(flightList[0], Airport(line2[0], line2[1], line2[2]), Airport(line3[0], line3[1], line3[2]))]
                    else:
                        allFlights.setdefault(flightList[1], [])
                        allFlights[flightList[1]] += [Flight(flightList[0], Airport(line2[0], line2[1], line2[2]), Airport(line3[0], line3[1], line3[2]))]
            else:
                allAirports.append(Airport(airList[0], airList[1], airList[2]))
    except:

        return False

def getAirportByCode(code):
    code1 = code
    for i in range (len(allAirports)):
        if code1 in str(allAirports[i]):
            return (str(allAirports[i]).replace(' ', ''))
    return -1

t1 = loadData("airports.txt", "flights.txt")
total = 0
for i in allFlights:
    total += len(allFlights[i])
print(t1)
if t1 and len(allAirports) == 37 and total == 146:
    print("Test 4 Passed. (loadData())")
else:
    print("Test 4 Failed. (loadData())")

当我运行代码返回假异常,即使当尝试是工作?谁能告诉我为什么这是不工作?或者如果我错过了什么。Idk它的while语句是问题,但idk什么改变它。请让我知道为什么假它打印在我的屏幕上。程序是为一个学校项目

vngu2lb8

vngu2lb81#

你怎么知道呢?我假设函数返回None,因为它没有其他的return语句,在下面的if语句中,t1None将被解释为False
总结如下:如果你的方法成功了你需要返回true。

相关问题