-3

您好我正在尝试创建一个基本的 python 程序来确定用户输入的日期是有效还是无效。我只是很难确定问题出在哪里并且已经解决了一段时间。任何帮助表示赞赏。到目前为止,这是我的代码。

def main():
#get the month day and year
(month, day, year)=eval(input("Enter month, day, and year numbers:"))
date1=str(month)+"/"+str(day)+"/"+str(year)
#determine if user inputted date is valid or invalid
def Valid (month, day, year): int(month) in range(0,12), int(day) in range(0,31), int(year) in range(0,100000)
def Verify (month, day, year):
    if (month, day, year) is Valid (month, day, year):
        print ((date1), "is a valid date.")
    else:
        print ("This is not a valid date.")

Verify (month, day, year)

(主要的)

4

1 回答 1

0

I'm only beginning Python so doubtless I'm not doing it correctly but, altering your code as little as possible, and leaving your lines in as comments before my suggestion:

#determine if user inputted date is valid or invalid 
def Valid (month, day, year):
    #int(month) in range(0,12), int(day) in range(0,31), int(year) in range(0,100000) 
    return int(month) in range(1,13) and int(day) in range(1,32) and int(year) in range(1,100000)

def Verify (month, day, year):
    #if (month, day, year) is Valid (month, day, year):
    if Valid (month, day, year):
        print ((date1), "is a valid date.")
    else:
        print ("This is not a valid date.")

#get the month day and year 
(month, day, year)=eval(input("Enter month, day, and year numbers:")) date1=str(month)+"/"+str(day)+"/"+str(year) 
Verify (month, day, year)

Be aware that "in range(0,12)" will return True for 0 to 11 and False for 12; you need (1,13) for the month test. Naturally this still thinks 29th Feb 1989 and 31st April are valid. Remember that years divisible by 4 are only leap years if the century is also divisible by 4, and there was no year 0 in normal usage.

于 2012-05-06T00:23:58.703 回答