Python:如果条件为真则跳过 For 循环中的迭代

问题描述 投票:0回答:1

我编写了一个 Python 脚本,它从 Excel 工作表中读取值并迭代行。

但是,我希望程序在满足特定条件时跳过一行。

我有一个 xml 文件,其中的值确定运行类型。在Python代码中,我编写了一个If / Else块来将值转换为数字(见下文)

# If / Else to convert test_run_type text to a value
if test_run_type == "Regression":
    test_run_type_value = '1'
elif test_run_type == "Smoke":
    test_run_type_value = '2'
elif test_run_type == "Sanity":
    test_run_type_value = '3'

接下来,我有一个循环遍历行的循环(参见下面的代码)

# Open Test Scenario Workbook; Instantiate worksheet object
wb = xlrd.open_workbook(os.path.join(test_case_directory, Product + '.xlsx'))
sh = wb.sheet_by_index(0)

## Begin For Loop to iterate through Test Scenarios
        i = 1
        rows = sh.nrows
        empty_cell = False
        for x in range(1, sh.nrows):

            cell_val = sh.cell(i, 0).value
            if cell_val == '':
                # If Cell Value is empty, set empty_cell to True
                empty_cell = True
            else:
                # If Cell Value is NOT empty, set empty_cell to False
                empty_cell = False


            regression_check = sh.cell_value(i, 3)
            smoke_check = sh.cell_value(i, 4)
            sanity_check = sh.cell_value(i, 5)

            # If / Else Section to check if a test needs to be run
            #### Program is running ALL rows & NOT skipping rows

            if test_run_type_value == 3 and sanity_check == "False":
                    continue
            else:
                pass

            if test_run_type_value == 2 and smoke_check == "False":
                    continue
            else:
                pass

            if test_run_type_value == 1 and regression_check == "False":
                    continue
            else:
                pass

问题:我的期望是,如果连续发生以下场景之一,程序将跳过一行。

  • test_run_type_value 为“3”且 sanity_check 等于 False
  • test_run_type_value 为“2”且 Smoke_check 等于 False
  • test_run_type_value 为“1”,regression_check 等于 False

但是,程序不会跳过任何行。

我截取了 Excel 工作表的屏幕截图。

enter image description here

根据工作表(参见附图),当 test_run_type_value 为“3”时,程序应跳过第一行,但事实并非如此。程序会迭代所有行(即使 test_run_type_value 为 1、2 或 3)

提前致谢

python excel for-loop if-statement continue
1个回答
0
投票
test_run_type_value = '1'

这会将

test_run_type_value
设置为 string
'1'

if test_run_type_value == 1 …

这会将

test_run_type_value
整数
1
进行比较。

所以你基本上是在这里比较字符串和整数,而它们永远不相等:

>>> '1' == 1
False

因此决定要使用字符串还是整数。例如。如果你指定

1
,它应该可以正常工作:

test_run_type_value = 1 # no quotes => int!

顺便说一句。你不需要这样做:

else:
    pass

只要不包含 else,如果条件不成立,则不会执行任何操作:

if test_run_type_value == 3 and sanity_check == "False":
    continue
if test_run_type_value == 2 and smoke_check == "False":
    continue
if test_run_type_value == 1 and regression_check == "False":
    continue
© www.soinside.com 2019 - 2024. All rights reserved.