IF循环的奇怪问题

时间:2015-03-16 19:17:10

标签: python loops

我的if循环有一个奇怪的问题,这是下面的代码:

def run_calculate(h,d,m,y):
    if m == 01:
        while True:
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 31:
                    calculate_and_write_hsdir(h,d,m,y)
                    d = 01
                    m = m + 1
                    y = y

    if m == 02:
        while True:
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 28:
                    calculate_and_write_hsdir(h,d,m,y)
                    d = 01
                    m = m + 1

    if m == 03:
        while True:
            print "In MARCH LOOP"
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 31:
                    calculate_and_write_hsdir(h,d,m,y)
                    print "March Done"
                    d = 01
                    m = m + 1

基本上我想要做的是每次每小时运行calculate_and_write_hsdir,在24小时之后它返回d(day)icremented by 1

我想要做的是停止它,因为它到达月底,但是如果我在jan 25开始它将工作正常直到它崩溃,但如果我开始它feb 01它也在2月29日崩溃了

我做错了什么?

这是我如何开始

h = 00 #Hour
d = 28 #Day
m = 8 #Month
y = 2013 #Year

run_calculate(h,d,m,y)
run_calculate(00,01,01,2014)
run_calculate(00,01,01,2015)

2 个答案:

答案 0 :(得分:0)

试试这个,你的while循环不会因为你的if语句而结束。完成后,您需要确保停止执行当前块。你也可以添加休息时间;

def run_calculate(h,d,m,y):
    if m == 01:
        while d <= 31:
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 31:
                    calculate_and_write_hsdir(h,d,m,y)
                    d = 01
                    m = m + 1
                    y = y

    if m == 02:
        while d <= 28:
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 28:
                    calculate_and_write_hsdir(h,d,m,y)
                    d = 01
                    m = m + 1

    if m == 03:
        while d <= 31:
            print "In MARCH LOOP"
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 31:
                    calculate_and_write_hsdir(h,d,m,y)
                    print "March Done"
                    d = 01
                    m = m + 1

答案 1 :(得分:0)

您的if m == x不在while True循环中。

因此,当您从m=1开始时,您将迭代到d=31,然后在同一循环中传递给m=2 。所以你试着再次迭代直到d == 31,这就是为什么程序在2月29日中断的原因。

你应该写:

def run_calculate(h,d,m,y):
    while True:
        if m == 01:
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 31:
                    calculate_and_write_hsdir(h,d,m,y)
                    d = 01
                    m = m + 1
                    y = y

        if m == 02:
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 28:
                    calculate_and_write_hsdir(h,d,m,y)
                    d = 01
                    m = m + 1

        if m == 03:
            print "In MARCH LOOP"
            d = calculate_and_write_hsdir(h,d,m,y)
            if d == 31:
                    calculate_and_write_hsdir(h,d,m,y)
                    print "March Done"
                    d = 01
                    m = m + 1

确保传递到if

的正确分支