Aaron Aaron - 5 months ago 42
Python Question

Getting an out of list assignment index out of range

Not sure why it is going out of range. I set the range from 0 to 5.
Here is my code

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)

Answer

That's because you're just creating a list with one element 5 in it. A better way to write this code might be

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))
Comments