2014-02-24 21 views
0

我一直在研究這個程序一段時間了。它是解決一個錯誤導致新問題的人之一。這是我最近的殘端。我有很多這樣的代碼句子,只有條件不一樣,但第二行仍然存在。在循環和條件內精確定位錯誤

if year % 400 == 0: 
    nyear = "leapyear" 

最後,我有這樣的代碼,它確保2月29日將只存在於閏年。這也是包含錯誤的代碼的一部分。

elif month == 2 and nyear == "leapyear": 
    if day > 29: 
     date = "invalid" 

這導致了最終的代碼,只打印有效日期:

if date != "invalid":  
    print(day, months[month], year) 
    break 
else: 
    continue  

我沒有張貼我的整個代碼,因爲它很長,但我還是可以的,如果添加它這會使問題更容易理解。這是我一直得到的錯誤,我不知道如何糾正它。

Traceback (most recent call last): 
    File "C:\Python33\assgn21.py", line 103, in <module> 
     main() 
    File "C:\Python33\assgn21.py", line 82, in main 
     elif month == 2 and nyear != "leapyear": 
UnboundLocalError: local variable 'nyear' referenced before assignment 

回答

3

如果你只有這一點:

if year % 400 == 0: 
    nyear = "leapyear" 
... 

然後,如果條件不滿足,你從來沒有設置nyear。相反,使它成爲一個標誌,並設置它在兩種情況下:

if year % 400: 
    leapyear = False 
else: 
    leapyear = True 

現在,你可以簡單地有:

elif month == 2 and leapyear: 

同樣,你應該有date_valid = False而非date = "invalid";它會讓你的代碼更清晰。