Ask the user how many days that they collected gems

Viewed 203

First time user here and newbie at programming. Ask the user how many days that they collected gems. A loop you write should loop how many days the user enters. If the user enters 5 days, then the loop should loop 5 times to collect the data from each day.

So, each loop iteration represents a day. In each loop iteration, ask the user how many gems they collected that day. After the loop finishes gathering the data for each day, calculate the total and average gems collected. Display the average as a float value.

Sample input/output (your output should match exactly): How many days did you collect gems? 5

Enter the number of gems collected on day 1: 5 Enter the number of gems collected on day 2: 4 Enter the number of gems collected on day 3: 3 Enter the number of gems collected on day 4: 2 Enter the number of gems collected on day 5: 1

Total gems collected: 15 Average gems collected per day: 3.00

I believe I have a lot of it right, but there is something wrong somewhere and I cannot figure it out.

days = int(input("How many days did you collect gems?"))

total = 0


for total in range(1, days + 1):
    gems = int(input("Enter the number of gems collected on day {0}:".format(total)))


total_gems = total + days + days
print("Total gems collected:","{0:.0f}".format(total_gems))

average_gems = float(total_gems / days)
print("Average gems collected per day:","{0:.2f}".format(average_gems))
2 Answers

Your code is close to being right, but your use of particular variables is a bit messed up and you don't preserve each of your daily inputs, but rather keep overwriting the previous day's entry by reassigning each time to gems without first doing something with the previous value. Here's an implementation that does what you want:

days = int(input("How many days did you collect gems?"))

total = 0

for day in range(1, days + 1):
    gems = int(input("Enter the number of gems collected on day {0}:".format(day)))
    total += gems

print("Total gems collected: {0}".format(total))

average_gems = float(total) / days
print("Average gems collected per day: {0:.2f}".format(average_gems))

Sample Run:

How many days did you collect gems?4
Enter the number of gems collected on day 1:6
Enter the number of gems collected on day 2:6
Enter the number of gems collected on day 3:2
Enter the number of gems collected on day 4:1
Total gems collected: 15
Average gems collected per day: 3.75

You're "clobbering" the total variable in the for loop because for total in range(1, days + 1): is re-using total. By way of example, the output of the following code is 9:

x = 1
for x in range(1, 10):
    pass
print(x)

Also, you're throwing away the gems variable after each iteration of the loop because you never use it anywhere.

You should change the variable for your loop to something other than total, and add gems to total inside the loop.

Related