【问题标题】:Trying to Figure out how to properly use a while loop in Python 3.3.0试图弄清楚如何在 Python 3.3.0 中正确使用 while 循环
【发布时间】:2013-03-10 14:54:16
【问题描述】:

我是 Python 的一个真正的菜鸟,我正在编写一个程序来输出给定日期是否是有效的日历日期。我确信有更优雅的方式来做到这一点。

此时,我试图弄清楚如何添加一个变量来创建一个 while 循环,该循环将处理日期,如果它是闰年或不是闰年。不过,所有建议都非常受欢迎。

我已将代码尝试的问题区域放在 中。这是我到目前为止的代码:

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

【问题讨论】:

  • 我看不出需要 while 循环。您正在检查给定日期是否正确。要么是,要么不是,你马上就知道了。此外,如果是闰年,这是一个无限循环(条件永远不会改变)。
  • @whoot 我知道这里有一个无限循环。看,在闰年,2 月有额外的一天,因此给定日期是否正确取决于年份。当然你可以通过看它来告诉它,但我正在尝试在这里编写一个程序,程序不能没有指令就告诉它。谢谢(在这里插入蟋蟀)。
  • 我试图通过指出第一步来帮助您:摆脱不正确的 while 循环。在我给你宝贵的时间免费帮助你的同时,你抱怨和谈论蟋蟀?
  • @whoot 我又看了一遍,你帮了大忙。对粗鲁感到抱歉。这不是借口,但我一直盯着这段代码太久了,没有睡觉。我只是使用了您建议的所有 if、elif 和 else 语句,并且效果很好。我仍然想知道如何使它与 while 语句一起工作,即使它是多余的。我非常感谢您的回答,当我重新审视所有内容时,它确实有所帮助。
  • @user2146060 已接受道歉。

标签: if-statement python-3.x while-loop


【解决方案1】:

我稍微完成了你的代码。希望从那里你可以不断改进它,朝着你想要的方向发展。

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

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2021-01-12
    • 2014-12-15
    • 2021-01-06
    • 2020-08-27
    • 1970-01-01
    • 2019-10-26
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多