即使设置为False,布尔也不会停止条件

时间:2017-05-03 10:32:23

标签: python while-loop boolean

对于此代码:

for crop in database:
    print("The current crop is :", crop)
    x.all_crop_parameters_match_the_PRA_ones = True     

    while x.all_crop_parameters_match_the_PRA_ones :

        ASSESS_Tmin( crop, x, PRA)

        print("x.all_crop_parameters_match_the_PRA_ones = ",  x.all_crop_parameters_match_the_PRA_ones)

        ASSESS_Water( crop, PRA, x)

        print("x.all_crop_parameters_match_the_PRA_ones = ",  x.all_crop_parameters_match_the_PRA_ones)

        ASSESS_pH(crop, PRA, x)

我得到以下结果:

The current crop is : FBRflx
Checking minimum Temperatures...
x.all_crop_parameters_match_the_PRA_ones =  False

Checking the Water Resources...
Verifying if the Water Resources match with the Tmin supported by the crop...
x.all_crop_parameters_match_the_PRA_ones =  False

The soil pH of this PRA matches to the crop requirements.
This crop is edible for the current PRA !

我不明白为什么程序会看到x.all_crop_parameters_match_the_PRA_ones为False并仍然运行下一个函数而不是打破循环并切换到下一个裁剪。

x是一个包含我使用的所有变量的类,修改是我的代码的几个函数。可能是一个错误,因为布尔值来自一个类?

1 个答案:

答案 0 :(得分:0)

你发布的内容对我来说就像是预期的行为。 while循环仅在执行其中的所有代码时重新评估条件...

如果你希望while代码在中间打破,请尝试放置休息:

for crop in database:
    print("The current crop is :", crop)
    x.all_crop_parameters_match_the_PRA_ones = True     

    while x.all_crop_parameters_match_the_PRA_ones :

        ASSESS_Tmin( crop, x, PRA)

        print("x.all_crop_parameters_match_the_PRA_ones = ",  x.all_crop_parameters_match_the_PRA_ones)

        if not x.all_crop_parameters_match_the_PRA_ones:
            break

        ASSESS_Water( crop, PRA, x)

        print("x.all_crop_parameters_match_the_PRA_ones = ",  x.all_crop_parameters_match_the_PRA_ones)

        if not x.all_crop_parameters_match_the_PRA_ones:
            break

        ASSESS_pH(crop, PRA, x)

请注意,它将在时间x.all_crop_parameters_match_the_PRA_ones == True的循环中。如果你只需要在while内执行一次代码,而不是在循环中,你可以尝试:

for crop in database:
    print("The current crop is :", crop)
    x.all_crop_parameters_match_the_PRA_ones = True     

    ASSESS_Tmin( crop, x, PRA)

    print("x.all_crop_parameters_match_the_PRA_ones = ",  x.all_crop_parameters_match_the_PRA_ones)

    if not x.all_crop_parameters_match_the_PRA_ones:
        continue

    ASSESS_Water( crop, PRA, x)

    print("x.all_crop_parameters_match_the_PRA_ones = ",  x.all_crop_parameters_match_the_PRA_ones)

    if not x.all_crop_parameters_match_the_PRA_ones:
        continue 

    ASSESS_pH(crop, PRA, x)