【发布时间】:2012-09-24 01:17:12
【问题描述】:
您好,我是 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 集合中的语句)代替。
如果您输入:month 为 2,day 为 30。它循环的消息是:
...30
而不是显示:
28
有人可以帮我弄清楚如何正确使用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 循环,但没有比这更高级的了。
程序应在程序结束时显示个人的出生日期。
【问题讨论】:
-
在您解决了 avasal 提出的问题后,我不确定如果满足条件,您的循环是否会中断。所以,如果你有
while(int(month)) in [4,6,9,11]:,你看起来好像没有在这里休息。 -
如果我不使用 in,但大多数情况下都满足,我只是遇到了“while”条件重叠的问题,就像我在问题中解释的那样。
-
看看glglgl的回答。他很好地解释了
while循环:)
标签: python loops if-statement while-loop boolean