簡體   English   中英

試圖弄清楚如何在Python 3.3.0中正確使用while循環

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

我是Python的天生菜鳥,我正在編寫一個程序,輸出給定日期是否為有效的日歷日期。 我敢肯定,還有更優雅的方法可以做到這一點。

在這一點上,我試圖弄清楚如何添加一個變量來創建一個while循環,該循環將處理the年或not年的日期。 盡管所有建議都是值得歡迎的。

我已將代碼嘗試的問題區域放在<>內。 這是我到目前為止的代碼:

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...

主要()

我已經稍微完成了您的代碼。 希望從那里可以繼續朝着您想要的方向改進它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM