-1

My current code:

mylist = [0] * 7     
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.")


 print (mylist)

best = max(mylist)
worst = min(mylist)
average = sum(mylist)/len(mylist)
total = sum(mylist)

print ("Your best day had", best, "in sales.")
print ("Your worst day had", worst, "in sales.")
print ("Your average daily sales were:", format(average,'.2f'))
print ("Your total sales were:", format(total, '.2f'))

When I run it I get this: the first one works, my question is about the second time i run it

Sales for day 0: 5
Sales for day 1:4
Sales for day 2:6
Sales for day 3:7
Sales for day 4:8
Sales for day 5:2
Sales for day 6:3
[5.0, 4.0, 6.0, 7.0, 8.0, 2.0, 3.0]
Your best day had 8.0 in sales.
Your worst day had 2.0 in sales.
Your average daily sales were: 5.00
Your total sales were: 35.00



Sales for day 0: 5
Sales for day 1:4
Sales for day 2:3
Sales for day 3:-4
Sorry,invalid. Try again.
Sales for day 3:four
Traceback (most recent call last):
line 44, in <module>
sales = float(input("Sales for day {0}:".format(x)))
ValueError: could not convert string to float: 'four'

How do I recode this so that python will also re-prompt the user to enter in another integer if they decide to say something like "four" instead of a number thanks alot.

David Robinson
  • 77,383
  • 16
  • 167
  • 187
user1762229
  • 71
  • 1
  • 6

3 Answers3

4

You can use try .. except. Here is a function that gets a float or prompts again:

def get_float(prompt):
    while True: 
        try:
            return float(input(prompt))
        except ValueError:
            print "invalid input, try again!"
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
0

I would suggest doing something like what was done in this answer which basically boils down to:
               use a try..except block

Community
  • 1
  • 1
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Use a function:

def get_int():
   sales = input("Enter a number :")
   if type(sales) == int or type(sales) == long: # Python 3.x doesn't have long-type objects
      # code to do whatever with sales
   else:
      print("Invalid input. Try again.")
      get_int()

It will keep calling it until you get a valid input.

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94