-2

Nooby 编码器在这里!我的任务是编写一些代码来打印任何给定日期的星期几。我的代码工作正常,但是当我运行任何格式不正确的东西(即“//2011”或“12/a/2011”)时,它会给我这个错误:

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

1 回答 1

0

首先,你输入一个没有月份的日期,你的程序会告诉你没有月份。这似乎不是什么大问题?

其次,您的两个示例实际上都会给出“错误:日期格式无效。”,而不是您声称的例外。你的最后一个例子。13/2/2011,将给出“13/2/2011 是无效日期。”,但如果您将其更改为有效日期,例如“12/2/2011”,它将给出“2011 年 2 月 13 日是星期日。”

因此,您的程序运行良好。

于 2011-12-11T09:21:27.917 回答