5

Why does my function fail to create lists?

 3 years ago
source link: https://www.codesd.com/item/why-does-my-function-fail-to-create-lists.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Why does my function fail to create lists?

advertisements

I am trying to create 5 lists out of 1 data file, the error I keep getting states that "airlines is not defined", yet it is the first thing I define in the function, how is this possible? What should I do to correctly create a list of airlines, arrival times, departure times, prices, and flight number?

USAir,1269,6:15,10:57,210
Delta,5138,16:20,22:10,212
UNITED,6001,14:12,20:50,217
Delta,5054,12:30,20:22,227
UNITED,5949,9:30,14:43,264
JetBlue,1075,17:00,20:06,280
Delta,1263,6:00,11:30,282
Delta,3824,9:00,14:45,282
USAir,1865,16:55,21:33,300
USAir,3289,18:55,23:41,300
USAir,1053,8:00,13:02,300
USAir,2689,12:55,18:09,300
USAir,3973,9:25,14:00,302
USAir,3267,11:30,16:13,302
USAir,3609,13:25,18:28,302
USAir,3863,15:35,20:54,302
USAir,3826,17:45,23:19,302
USAir,1927,7:00,12:53,302
Delta,3601,12:00,17:29,307
Delta,4268,7:15,12:46,307
UNITED,4676,6:00,10:45,321
UNITED,4103,11:00,16:16,321
USAir,3139,11:51,16:29,332
JetBlue,475,7:30,10:42,340
USAir,3267,11:30,18:15,367
UNITED,2869,16:55,21:33,406
UNITED,2865,6:15,10:57,406
UNITED,2729,8:00,13:02,406
UNITED,2645,7:00,12:53,445

and the code I am using is

def getFlights():

    airlines = []
    flightNums = []
    depTimes = []
    arriveTimes = []
    prices = []

    fname = input("Enter name of data file: ")
    infile = open(fname, 'r')

    line = infile.readline()
    line = line.strip()

    while line != "":
        line = line.strip()
        airline, flightNum, depTime, arriveTime, price = line.split(',')
        airlines.append(airline)
        flightNums.append(flightNum)
        depTimes.append(depTime)
        arriveTimes.append(arriveTime)
        prices.append(price)
        line = infile.readline()
        line = line.strip()

    infile.close()
    return airlines, flightNums, depTimes, arriveTimes, prices

getFlights()
print(airlines, flightNums, depTimes, arriveTimes, prices)


Local variables inside a function are not accessible outside of the function call. If you want to use the returned values of getFlights you must assign them to variables in the calling context.

(airlines, flightNums, depTimes, arriveTimes, prices) = getFlights()
print(airlines, flightNums, depTimes, arriveTimes, prices)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK