2011-12-11 154 views
-2

Nooby編碼器在這裏!我的任務是編寫能夠打印任何給定日期的星期幾的內容。我的代碼工作正常,但是當我運行任何不正確的格式(即「// 2011」或「12/A/2011」),它會給我這個錯誤:Python 3.2 UnboundLocalError日期到星期幾轉換器

line 55, in main if is_date_valid(month, day, year) == False: 
UnboundLocalError: local variable 'month' referenced before assignment 

雖然如果我嘗試「13/2/2011」,運行良好。請幫助我找到我的問題,因爲我的老師在向我詢問時不知道解決方案! 這裏是(如有必要,無視我的評論:p)全碼 非常感謝你:d

import sys 
DAYS_IN_MONTH = ('31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31') 
MONTHS_IN_WORDS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") 
DAYS_OF_WEEK = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') 

def get_date(): 
    str_date = input('Enter date: ')#.strip() = method :D 
    parts = str_date.split('/')#pasts = ['12', '2', '2011'] 
    length = len(parts) 
    if length != 3: 
     raise ValueError('Invalid format for date.') 
    for i in range(length): 
     parts[i] = parts[i].strip() 
     if len(parts[i]) == 0 or not(parts[i].isdigit()): 
      raise ValueError('Invalid format for date.') 
    return(int(parts[0]), int(parts[1]), int(parts[2])) 

def is_date_valid(month, day, year): #is_date_valid = name of function 
    if month < 1 or month > 12 or day < 1 or year < 0: 
     return False 
    if month != 2: 
     return int(day) <= int(DAYS_IN_MONTH[month-1]) 
    additional = 0 
    if year % 400 == 0 or year % 4 == 0 and year % 100 != 0: 
     additional = 1 
    return int(day) <= int(DAYS_IN_MONTH[1]) + int(additional) 

#month, day, year = arguments of function 

def date_as_string(month, day, year): 
    if month > 0 and month < 13: 
     return MONTHS_IN_WORDS[month-1] + ' ' + str(day) + ', ' + str(year) 


def day_of_week(month, day, year): 
    if month < 3: 
     month += 12 
     year -= 1 
    m = month 
    q = day 
    J = year // 100 
    K = year % 100 
    h = (q + 26*(m+1)//10 + K + K//4 + J//4 - 2*J) % 7 
    dayweek = DAYS_OF_WEEK[h-2] 
    return dayweek 

def main(): 
    print('This program calculates the day of the week for any date.') 
    try: 
     (month, day, year) = get_date() 
    except ValueError as error: 
     print("ERROR:", error) 
     sys.exit(1) 
    if is_date_valid(month, day, year) == False: 
     print(str(month) + '/' + str(day) + '/' + str(year) + ' is an invalid date.') 
     print() 

    else: 
     print(date_as_string(month, day, year) + ' is a ' + day_of_week(month, day, year) + '.') 
     print() 



#any function call that can raise an error must be put inside a try block 
if __name__ == '__main__': 
    main() 

回答

0

首先,你輸入一個日期,沒有一個月,你的程序會告訴你,你不必一個月。這似乎不是一個很大的問題?其次,你的兩個例子實際上會給出一個「錯誤:日期格式無效」,而不是你聲稱的例外。你最後一個例子。 2011年2月13日,將給出「2011年2月13日是無效日期」,但如果您將其更改爲有效日期,如「2011年2月2日」,則會給出「2011年2月13日是星期日「。

因此,您的程序運行完美。