Sunday, 15 May 2011

python - Why aren't the lists populating in this code? -



python - Why aren't the lists populating in this code? -

i wrote code class , cannot figure out why lists not populating values. i've tried using debugger , still can't figure out why won't work. ideas? also... know loops have made more sense, needed utilize while loops assignment.

__author__ = 'ethan' #this programme reads in file user contains lines of def mileage(): filename = input("please come in file name: ") file = open(filename,"r") line_list = [] num_lines = sum(1 line in file) line_counter = 0 while line_counter <= num_lines: line = file.readline() line_items = line.split() line_list.append(line_items) line_counter += 1 current_index_pos = 0 while current_index_pos <= num_lines: current_item = line_list[current_index_pos] print("leg",current_index_pos + 1,"---", current_item[0]/current_item[1],"miles/gallon") current_index_pos += 1 mileage()

this reads end of file

num_lines = sum(1 line in file)

so there no lines left read when here

line = file.readline()

better construction code this

with open(filename, "r") fin: line_counter, line in enumerate(fin): line_items = line.split() line_list.append(line_items) # after loop line_counter has counted lines

or (if don't need line_counter)

with open(filename, "r") fin: line_list = [line.split() line in fin]

more advanced utilize generator look or in single loop avoid needing read whole file memory @ once

def mileage(): filename = input("please come in file name: ") open(filename, "r") fin: line_counter, line in enumerate(fin): current_item = line.split() print("leg",line_counter + 1,"---", float(current_item[0])/float(current_item[1]),"miles/gallon")

python list while-loop

No comments:

Post a Comment