-2

ヌービーコーダーはこちら!私の課題は、特定の日付の曜日を出力するコードを作成することです。私のコードは正常に動作していますが、正しい形式 (つまり、「//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 は無効な日付です。」となりますが、「2011 年 12 月 2 日」のように有効な日付に変更すると、「2011 年 2 月 13 日は日曜日です」となります。 ."

したがって、プログラムは完全に機能しています。

于 2011-12-11T09:21:27.917 に答える