如何让我的for循环继续从它在try和except块中停止的地方继续? Python 3

时间:2017-05-05 06:53:13

标签: python for-loop python-3.5 try-except

如果用户输入的号码没有输入,我希望我的程序能够收到错误。如果用户输入一个字母或只是按“输入”,程序将从头开始重新启动for循环。如何从输入错误的地方开始?

#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") 

3 个答案:

答案 0 :(得分:2)

您可以使用其他变量来跟踪用户给出的答案:

#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()

在这种情况下ANSWERS

答案 1 :(得分: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)

答案 2 :(得分:0)

这是一个更清洁的答案:

ItemLoader