0

I want my program to catch an error if a number isn't entered by the user. If the user enters a letter or just presses 'enter', the program restarts the for loop from the beginning again. How can I make it start from the place it was entered wrong?

#This is the size of the array 
YEAR_SIZE = 12

months = []                     ###This is the array that will hold the rainfall for each month 
monthNames=['January','February','March','April','May',
'June','July','August','September',
'October','November','December']

def getMonthlyRainfall():
  while True:
    try:
      total = 0
      for month in range(YEAR_SIZE):         ###This loop iterates 12 times for 12 entries
         print ("Enter the rainfall for",monthNames[month], "in inches")
         months.append(float(input()))
         continue
    except:
      print ("Try again") 
Community
  • 1
  • 1

3 Answers3

2

You could use another variable to keep track of the answers given by the user:

#This is the size of the array 
YEAR_SIZE = 12

months = []                     ###This is the array that will hold the rainfall for each month 
monthNames=['January','February','March','April','May',
'June','July','August','September',
'October','November','December']


def getMonthlyRainfall():
    ANSWERS = 0

    while True:
        try:
            total = 0
            for month in range(ANSWERS, YEAR_SIZE):         ###This loop iterates 12 times for 12 entries
                print ("Enter the rainfall for",monthNames[month], "in inches")
                x = input()
                months.append(float(x))
                ANSWERS = ANSWERS + 1
        except:
          print ("Try again") 

getMonthlyRainfall()

In this case ANSWERS

0

Check online Demo

YEAR_SIZE = 12

months = []                     ###This is the array that will hold the rainfall for each month 
monthNames=['January','February','March','April','May',
'June','July','August','September',
'October','November','December']

def getMonthlyRainfall():
  while True:
    total = 0
    for month in range(YEAR_SIZE):         ###This loop iterates 12 times for 12 entries1
       try:

         tmp = get_input(month)
       except ValueError:
         print ("Enter the rainfall for",monthNames[month], "in inches")
         tmp = get_input()
       months.append(tmp)
       continue

def get_input(month):
  try:
    print ("Enter the rainfall for",monthNames[month], "in inches")
    tmp = float(input())
  except ValueError:
    get_input(month)
Himanshu dua
  • 2,496
  • 1
  • 20
  • 27
  • Careful ! This program will crash due to Recursion if the user inputs too much wrong values. – Morreski May 05 '17 at 09:44
  • @Morreski No it will not crash.I have tried more than 100 wrong values. – Himanshu dua May 05 '17 at 10:21
  • It is true that the user is unlikely to fail more than 4 or 5 times. But it is a bad practice to use recursion when processing incoming data. Recursion in python is dangerous. See [this thread](http://stackoverflow.com/questions/3323001/what-is-the-maximum-recursion-depth-in-python-and-how-to-increase-it) for more infos. – Morreski May 05 '17 at 13:15
0

Here is a cleaner answer:

import calendar

def ask_for_rainfall(month_name):
    while True:
        try:
            return float(input("Enter the rainfall for %s in inches" % month_name))
        except:
            print('Try again')

def get_monthly_rain_fall():
    month_names = list(calendar.month_name[1:])
    return {m_name: ask_for_rainfall(m_name) for m_name in month_names}

# Now you can do
# rain_falls = get_monthly_rain_fall()
# print(rain_falls["January"])
Morreski
  • 302
  • 1
  • 5
  • So, It's my first time posting a question and I never got in my email the replies, resulting in me not seeing this until now. I made different changes and got it to work with a while loop replacing the for statement. – Eduardo Guzman May 05 '17 at 23:29
  • 1
    I'm going to try this out either way for future references. Thank you for the feedback! It certainly seems much better than what I had. One can never know too much. Once again, thank you – Eduardo Guzman May 05 '17 at 23:30