2016-06-13 69 views
0

不確定它爲什麼超出範圍。餘設置的範圍從0到5 這是我的代碼獲取列表分配索引超出範圍

class Car(object): 
    def __init__ (self, price, speed, fuel, mileage): 
     self.price = price 
     self.speed = speed 
     self.fuel = fuel 
     self.mileage = mileage 
     self.price = price 
     if price > 1000: 
      self.tax = 15 
     else: 
      self.tax = 12 
    def displayAll(self): 
     print "Price: " + str(self.price) 
     print "Speed: " + str(self.speed) 
     print "Fuel: " + str(self.fuel) 
     print "Mileage: " + str(self.mileage) 
     print "Tax: 0." + str(self.mileage) 

auto = [5] 
for car in range(0,5): 
    price = input("How much does the car cost? ") 
    speed = input("Mile per hour? ") 
    mileage = input("Mile per gallon? ") 
    fuel = raw_input("How much fuel? ") 
    print car 
    auto[car] = Car(price, speed, fuel, mileage) 
+0

從一個空列表開始,並使用'append()'。 –

回答

2

當那是因爲你剛剛創建其中包含一個元素5的列表。編寫此代碼的更好方法可能是

auto = [] 
for car in range(0,5): 
    price = input("How much does the car cost? ") 
    speed = input("Mile per hour? ") 
    mileage = input("Mile per gallon? ") 
    fuel = raw_input("How much fuel? ") 
    print car 
    auto.append(Car(price, speed, fuel, mileage)) 
1

自動被一個條目的矩陣,即數字5,即[5]。你希望它是一個有5個條目的矩陣。

0

您可以設置自動向auto=[5],但它應該是auto=[None]*5auto=range(5)

否則你創建長度爲1的列表,並會得到一個出界失誤調用auto[car]