简体   繁体   中英

Trying to Figure out how to properly use a while loop in Python 3.3.0

I am a bonafied noob at Python and I am writing a program that outputs whether a given date is a valid calendar date or not. I'm sure that there is much more elegant way to do it.

At this point I'm trying to figure out how I can add a variable to create a while loop that will take care of the date if it is either a leap year or not a leap year. All suggestions are quite welcome though.

I've put the problem areas of my code attempt inside <>. Here is the code I have so far:

def main():
print("This program tests the validity of a given date")

date = (input("Please enter a date (mm/dd/yyyy): "))
month, day, year = date.split("/")
month = int(month)
day = int(day)
year = int(year)
Mylist31 = [1, 3, 5, 7, 8, 10, 12]
Mylist30 = [4, 6, 9, 11]

#Calculates whether input year is a leap year or not
if year >= 100 and year % 4 == 0 and year % 400 == 0:
    <it is a leap year>
elif year >= 0 and year <100 and year % 4 == 0:
    <it is a leap year>
else: 
    <it is not leapyear>


while <it is a leapyear>:
    if month in Mylist31 and day in range(1, 32):
        print("Valid date")
    elif month in Mylist30 and day in range(1,31):
        print("Valid date")
    elif month == 2 and day in range(1,30):
        print("Valid date")
    else:
        print("Not a Valid date")  
while <it is not a leapyear>:
etc...

main()

I've slightly completed your code. Hopefully from there you can keep improving it towards what you wanted.

def main():
    print("This program tests the validity of a given date")

    date = (raw_input("Please enter a date (mm/dd/yyyy): "))
    month, day, year = date.split("/")
    month = int(month)
    day = int(day)
    year = int(year)
    Mylist31 = [1, 3, 5, 7, 8, 10, 12]
    Mylist30 = [4, 6, 9, 11]

    ##Calculates whether input year is a leap year or not
    if year >= 100 and year % 4 == 0 and year % 400 == 0:
        is_leap_year = True
    elif year >= 0 and year <100 and year % 4 == 0:
        is_leap_year = True
    else:
        is_leap_year = False

    if is_leap_year:
        if month in Mylist31 and day in range(1, 32):
            print("Valid date")
        elif month in Mylist30 and day in range(1,31):
            print("Valid date")
        elif month == 2 and day in range(1,30):
            print("Valid date")
        else:
            print("Not a Valid date")
    else:
        #TODO: validate non-leap-year date
        pass

main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM