2014-02-15 92 views
0

這是我的程序。關於如何讓整個事物循環的任何想法,但只有當輸入不正確時我已經爲範圍設置了一個大整數,但我無法弄清楚在哪裏以及如何設置條件來實現它。到目前爲止我嘗試過的所有東西都給了我一個錯誤。任何幫助將不勝感激。Python中循環3

def main(): 

    for i in range(1000): 

    date = (input("enter the date as dd/mm/yyyy: ")) 

    try: 
     datetime.datetime.strptime(date,"%d/%m/%Y") 
     print ("Format is Correct") 
    except: 
     ValueError 
     print ("Format is Incorrect") 

    date = day, month, year = date.split("/") 
    if len(day) == 1 or len(day) == 2: 
     day = int(day) 
     if len(month) == 1 or len(month) == 2: 
      month = int(month) 
      months = ["emp", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", 
         "Aug", "Sep", "Oct", "Nov", "Dec"] 
      if len(year) == 4: 
       year = int(year) 
       if 1899 < year < 3001: 
        if year % 100 == 0: 
         if year % 400 == 0: 
          print ("It's a leap year") 
         else: 
          print ("It is not a lea[ year") 
        else: 
         if year % 4 == 0: 
          print ("It's a leap year") 
         else: 
          print ("It is not a leapyear") 
       else: 
        print ("The year is not in range") 
       if month > 12 or month < 0: 
        print ("The month is out of range") 
       elif month == 4 or month == 6 or month == 9 or month == 11: 
        if day > 30: 
         print ("The date is out of range for the month") 
       elif month == 2: 
        if day > 29: 
         print ("The date is out of range for the month") 
       print(day, months[month], year)    

main() 
+0

不要與你的循環一個大的整數使用。你可以使用'while(condition)'做你的東西,並且設置好條件,你甚至不需要在你的循環中使用'continue'關鍵字,但是在你的程序中使用它是個壞主意。 –

+0

@HamidFzM你可以舉一個如何在這個特定情況下使用while循環的例子嗎? – Manaar

回答

1

只需使用continue回到循環的開頭:

try: 
    datetime.datetime.strptime(date,"%d/%m/%Y") 
    print ("Format is Correct") 
except ValueError: 
    print ("Format is Incorrect") 
    continue 
+0

將繼續放在那裏會導致程序繼續循環,即使輸入是corect – Manaar

+1

@Manaar這不可能是真的。你的縮進是正確的嗎? – SethMMorton

+2

@sashkello我推薦'除了ValueError:',因爲它似乎是原始代碼中OP的意圖。 – SethMMorton