Reputation: 71
This is my current code:
while True:
try:
mylist = [0] * 7
for x in range(7):
sales = float(input("Sales for day:"))
mylist[x] = sales
if sales < 0:
print ("Sorry,invalid. Try again.")
except:
print ("Sorry, invalid. Try again.")
else:
break
print (mylist)
best = max(sales)
worst = min(sales)
print ("Your best day had", best, "in sales.")
print ("Your worst day had", worst, "in sales.")
When I run it I get this:
Sales for day:-5
Sorry,invalid. Try again.
Sales for day:-6
Sorry,invalid. Try again.
Sales for day:-7
Sorry,invalid. Try again.
Sales for day:-8
Sorry,invalid. Try again.
Sales for day:-9
Sorry,invalid. Try again.
Sales for day:-2
Sorry,invalid. Try again.
Sales for day:-5
Sorry,invalid. Try again.
[-5.0, -6.0, -7.0, -8.0, -9.0, -2.0, -5.0]
Traceback (most recent call last):
File "C:/Users/Si Hong/Desktop/HuangSiHong_assign9_part.py", line 45, in <module>
best = max(sales)
TypeError: 'float' object is not iterable
I am not quite sure how to code it so that, the lists do NOT take in negative values, because I only want values 0 or greater.
I am not sure how to solve the TypeError issue so that the min and max values will print as in my code
My last issue is, if I want to find the average value of the seven inputs that an user puts in, how should I go about this in pulling the values out of the lists
Thank you so much
Upvotes: 1
Views: 93
Reputation: 1959
maybe (untested):
mylist = []
while len(mylist) < 7:
sales = float(input("Sales for day %s:" % str(len(mylist)+1)))
if sales >= 0:
mylist.append(sales)
else:
print ("Sorry,invalid. Try again.")
print (mylist)
best = max(mylist)
worst = min(mylist)
print ("Your best day had", best, "in sales.")
print ("Your worst day had", worst, "in sales.")
Upvotes: -1
Reputation: 39698
Your best bet is to put the data checking into a while loop. This will keep looping over this value until your conditions are met (>0
)
Also, this could get confusing for the user to figure out what day they are entering the results for. Plus you need to be using the list for the max/min, not individual values. Put it all together, and make the following changes:
for x in range(7):
sales=-1
while (sales<0):
sales = float(input("Sales for day {0}".format(x)))
mylist[x] = sales
if sales < 0:
print ("Sorry,invalid. Try again.")
And later make this change:
best = max(my_list)
worst = min(my_list)
Upvotes: 3
Reputation: 500257
Did you mean to say:
best = max(my_list)
worst = min(my_list)
As to the validity check, the problem there is that if the input is invalid, you still move on to the next value of x
.
Upvotes: 3