0

嗨,我是 python 的初学者,我正在尝试创建一个程序,在其中输入日期并在程序中显示

当用户输入超出限制的数字时,我尝试实现循环。为了确定月份,while 循环运行良好:

month = int(input("Which numeric month of the year were you born in?\n"))
while((month <=0) or (month >12)):
    print("The Month must be within the range 12>= Month >0. Please enter the value again.")
    print("\n")
    month = int(input("Which numeric month of the year were you born in?\n"))

但是,对于第二部分(如下),确定日期时,当用户输入限制为 28 天的 2 月份的值时,它显示的循环消息是针对不同的条件(第三个 if 语句在day设置)代替。

如果您输入: 2 代表month, 30 代表day。它循环的消息是:

...30< 月 =<0

而不是显示:

28< 月 =<0

有人可以帮我弄清楚如何正确使用while语句吗?

我的代码如下:

day = int(input("Which numeric day of the month were you born in?\n"))
while(month == 1,3,5,7,8,10,12):
    if(day <=0) or (day >31):
        print("For your selected month, the value for day must be within the range 31>= Day >0. Please enter the value again.")
        print("\n")
        day= int(input("Which numeric day of the month were you born in?\n"))
while(month ==2):
    if(day <=0) or (day >28):
        print("For your selected month, the value for day must be within the range 28>= Day >0. Please enter the value again.")
        print("\n")
        day= int(input("Which numeric day of the month were you born in?\n"))
while(month ==4,6,9,11):
    if(day <=0) or (day >30):
        print("For your selected month, the value for day must be within the range 30>=Day>0. Please enter the value again.")
        print("\n")
        day= int(input("Which numeric day of the month were you born in?\n"))

请注意,在使用它时,我仅限于初学者级别的 python 代码。除此之外,我能做的最多的是使用for循环而不是while循环,但没有比这更高级的了。

程序应在程序结束时显示个人的出生日期。

4

1 回答 1

3

你有太多的while循环。其中一些你永远无法逃脱。

在你知道你有哪个月之后,你应该决定这个月有多少天:

所以你有了

month = int(input("Which numeric month of the year were you born in?\n"))
while((month <=0) or (month >12)):
    print("The Month must be within the range 12>= Month >0. Please enter the value again."):
    print("\n")
    month = int(input("Which numeric month of the year were you born in?\n"))
if month in (4, 6, 9, 11): # short
    maxdays = 30
elif month != 2: # not February -> long
    maxdays = 31
else:
    # Here we could ask for the year, determine if the year is divisible by 4, by 100 and by 400 and with this information determie if we have a leap year, but...
    # we are tolerant for now and accept the 29 as well.
    maxdays = 29

现在,您可以使用现有的东西而不会经常重复自己:

day = int(input("Which numeric day of the month were you born in?\n"))
if(day <= 0) or (day > maxdays):
    print("For your selected month, the value for day must be within the range {0} >= Day > 0. Please enter the value again.".format(maxdays))
    print("\n")
    day = int(input("Which numeric day of the month were you born in?\n"))

如果你还没有学过format(),你可以做

    print("For your selected month, the value for day must be within the range " + str(maxdays) + " >= Day > 0. Please enter the value again.")

甚至

    print("For your selected month, the value for day is wrong. Please enter the value again.")
于 2012-10-03T06:45:03.207 回答