繁体   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