【问题标题】:Looping in Python 3Python 3 中的循环
【发布时间】:2014-02-15 03:48:44
【问题描述】:

这是我的程序。关于如何使整个事情循环的任何想法,但前提是输入不正确?我已经为范围设置了一个大整数,但我不知道在哪里以及如何设置条件来实现它。到目前为止,我尝试过的一切都给了我一个错误。任何帮助将不胜感激。

def main():

  for i in range(1000):

    date = (input("enter the date as dd/mm/yyyy: "))

    try:
        datetime.datetime.strptime(date,"%d/%m/%Y")
        print ("Format is Correct")
    except:
        ValueError
        print ("Format is Incorrect")

    date = day, month, year = date.split("/")
    if len(day) == 1 or len(day) == 2:
        day = int(day)
        if len(month) == 1 or len(month) == 2:
            month = int(month)
            months = ["emp", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
                      "Aug", "Sep", "Oct", "Nov", "Dec"]
            if len(year) == 4:
                year = int(year)
                if 1899 < year < 3001:
                    if year % 100 == 0:
                        if year % 400 == 0:
                            print ("It's a leap year")
                        else:
                            print ("It is not a lea[ year")
                    else:
                        if year % 4 == 0:
                            print ("It's a leap year")
                        else:
                            print ("It is not a leapyear")
                else:
                    print ("The year is not in range")
                if month > 12 or month < 0:
                    print ("The month is out of range")
                elif month == 4 or month == 6 or  month == 9 or month == 11:
                    if day > 30:
                        print ("The date is out of range for the month")
                elif month == 2:
                    if day > 29:
                        print ("The date is out of range for the month")
                print(day, months[month], year)            

main()

【问题讨论】:

  • 不要在循环中使用带有大整数的 for。您可以使用while(condition) 来做您的事情,并且通过设置良好的条件,您甚至不需要在循环中使用continue 关键字,但在您的程序中使用 for 是个坏主意。
  • @HamidFzM 您能否举例说明如何在这种特定情况下使用 while 循环?

标签: python loops for-loop python-3.x


【解决方案1】:

只需使用continue 回到循环的开头:

try:
    datetime.datetime.strptime(date,"%d/%m/%Y")
    print ("Format is Correct")
except ValueError:
    print ("Format is Incorrect")
    continue

【讨论】:

  • 将 continue 放在那里会导致程序继续循环,即使输入正确
  • @Manaar 这不可能。你的缩进正确吗?
  • @sashkello 我推荐except ValueError:,因为这似乎是原始代码中 OP 的意图。
  • @SethMMorton 谢谢,已修复。
猜你喜欢
  • 2012-09-21
  • 2016-12-31
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多