Python“if”语句被忽略

时间:2013-01-29 10:40:28

标签: python loops if-statement for-loop logical-operators

  

可能重复:
  Multiple conditions with if/elif statements

如果满足多个条件之一(“或”),我在Python中触发循环循环。 该脚本似乎跳过“if”语句并进入内部循环而不满足所需条件。

代码

# Begin TestCase
# Main logic: execute RemoteController macro, if expected state == true, set 'Success', else: Fail
for macroname_n in range (32):
    handler("RemoteController", "SET", "[{0}_{1}_{2}]".format(testcase, macroname_n, platform), "")
    result = pbc_json(disk, testcase_area, testcase, platform, filename_n, coord_n)
    filename_n += 1
    coord_n += 1
    if macroname_n == 15 or 20:
        success_counter = 0
        for extra_loop in range(15):
            handler("RemoteController", "SET", "\"down 4\"", "")
            result = pbc_json(disk, testcase_area, testcase, platform, filename_n, coord_n)
            filename_n += 1
            if result >= 50:
                success_counter += 1
        if success_counter <> 15:
            result = 0

提前致谢!

3 个答案:

答案 0 :(得分:11)

此行无法执行您想要的操作:

if macroname_n == 15 or 20:

解析如下:

if (macroname_n == 15) or (20):

由于20在布尔上下文中始终为true,因此该语句始终为true。你真正想要的是这个:

if macroname_n in (15, 20):

答案 1 :(得分:3)

20始终在布尔上下文中求值为true。因此,macroname_n == 15 or 20始终为true

你可能想写:

if macroname_n == 15 or macroname_n == 20:
    success_counter = 0
    # ...

答案 2 :(得分:1)

if macroname_n == 15 or 20:

应该是:

 if macroname_n == 15 or macroname_n == 20:

否则它将始终读为20为真。