Skip to content
Advertisement

Creating a list with user input? Sales program, enter sales for 7 days

So the problem is this:

Design a program that asks the user to enter a store’s sales for each day of the week. The amounts should be stored in an array. Use a loop to calculate the total sales for the week and display the result.

This is what I have so far,

maxValue = 7
sales = 0
index = 0
totalSales = [maxValue]

for index in range(0, maxValue - 1):
    totalSales[index] = float(input("Enter today's sales: $"))

I know it’s in issue with bounds, I am getting the error IndexError: list assignment index out of range after I enter my second input.

After debugging I can see that totalSale = [maxValue] is giving the list a length of one.. but I don’t understand how to fix this. I appreciate the help!

Advertisement

Answer

The problem with your code is at this line:

totalSales = [maxValue]

The line basically sets [7] to the variable totalSales. What you are looking for is the * operation on a list to generate a list of your desired length filled with null (None) values:

maxValue = 7
sales = 0
index = 0
totalSales = [None] * maxValue

for index in range(maxValue):
    totalSales[index] = float(input("Enter today's sales: $"))

Or better, use the list.append() method:

maxValue = 7
sales = 0
index = 0
totalSales = []

for index in range(maxValue):
    totalSales.append(float(input("Enter today's sales: $")))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement