2016-04-24 27 views
-2

我一直在尋找遍地,我不明白爲什麼我一直得到相同的錯誤。我已經讀過,它與'返回'有關,但對我來說沒有意義。Python - 「'NoneType'對象不可迭代」錯誤將值賦值給循環中的def

Traceback: 
    File "/tmp/vmuser_mlgewmyusy/main.py", line 47, in daysBetweenDates 
    new_year,new_month,new_day=nextDay(new_year,new_month,new_day) 
TypeError: 'NoneType' object is not iterable 

代碼:

def nextDay(year, month, day): 
if month!=12: 
    if month==1 or month==3 or month==5 or month==7 or month==8 or month==10: 
     if day!=31: 
      return year,month,day+1 
     else: 
      return year,month+1,1 
    elif month==4 or month==6 or month==9 or month==11: 
     if day!= 30: 
      return year,month,day+1 
     else: 
      return year,month+1,1 
    elif month==2: 
     if day!= 28: 
      return year,month,day+1 
     else: 
      return year,month+1,1 
    elif month==22: 
     if day!= 29: 
      return year,month,day+1 
     else: 
      return year,month+1,1 
    else: 
     if day!= 31: 
      return year,month,day+1 
     else: 
      return year+1,1,1 

def daysBetweenDates(year1, month1, day1, year2, month2, day2): 
    i=0 
    new_year,new_month,new_day=year1-100,month1-100,day1-100 
    if year1==year2 and month1==month2 and day1==day2: 
     return 0 
    while new_year!=year2 and new_month!=month2 and new_day!=day2: 
     if i==0: 
      `new_year,new_month,new_day`=year1+100,month1+100,day1+100 
     i+=1 
     new_year,new_month,new_day=nextDay(new_year,new_month,new_day) 
    return i 

# Test routine 

def test(): 
    test_cases = [((2012,1,1,2012,2,28), 58), 
        ((2012,1,1,2012,3,1), 60), 
        ((2011,6,30,2012,6,30), 366), 
        ((2011,1,1,2012,8,8), 585), 
        ((1900,1,1,1999,12,31), 36523)] 
    for (args, answer) in test_cases: 
     result = daysBetweenDates(*args) 
     if result != answer: 
      print "Test with data:", args, "failed" 
      print 'ANSWER = {}'.format(answer) 
      print 'RESULT = {}'.format(result) 
     else: 
      print "Test case passed!" 

test() 

我想一個新值每次分配 'new_year,new_month,new_day' 循環迭代。

+0

你能告訴你如何調用這些函數嗎? – vmonteco

+0

爲什麼你不使用datetime庫? – Mikaelblomkvistsson

+0

這是一門課程,我不能使用任何圖書館 – Luigi

回答

0

我添加了這兩個打印行到daysBetweenDates功能:

... 
if i==0: 
     new_year,new_month,new_day=year1+100,month1+100,day1+100 
    i+=1 
    print(new_month) 
    print(nextDay(new_year,new_month,new_day)) 
    new_year,new_month,new_day=nextDay(new_year,new_month,new_day) 
...  

我試試這個輸入daysBetweenDates(2015,6,1,2014,4,1),發現print(new_month)106print(nextDay(new_year,new_month,new_day))None。查看nextDay的代碼塊,沒有條件趕上month==106,因此該函數返回Python默認值None

儘管您的值可能會有所不同,但看起來new_month不在集合{1,2,3,4,5,6,7,8,9,10,11,22}中,所以函數正在返回None這就是你的錯誤來自何處。所以你可以確保總是返回一個元組,或者調試你的代碼,看看爲什麼你得到的輸入數據與你編碼的數據不同。

相關問題