简体   繁体   中英

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!

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: $")))
maxValue = 7
sales = 0
index = 0
totalSales = list() 

[maxValue] would add just one item of value maxValue to the list. Append adds new items to the list. For range, you can just use the maxValue as a parameter, no need for (0, maxValue)

for index in range(maxValue):
    totalSales.append(float(input("Enter today's sales: $")))

As stated by Adam.Er8, use the append() function to add the entries to the list. You almost had it, Also, the call to the range() function will exclude the "nth" index, so you do not need to subtract one from maxValue to get 7 entries. Example below:

total_sales = []
for ix in range(0, maxValue):
    totalSales.append(float(input("Enter today's sales: $")))

# results below
# Enter today's sales: $10
# Enter today's sales: $5
# Enter today's sales: $10
# Enter today's sales: $1
# Enter today's sales: $1
# Enter today's sales: $2
# Enter today's sales: $3

# total_sales
# [10.0, 5.0, 10.0, 1.0, 1.0, 2.0, 3.0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM