2017-08-02 252 views
0

我已经编写了一个Python脚本,该脚本从Excel工作表中读取值并遍历行。Python:如果条件为真,跳过For循环中的迭代

但是,如果满足某些条件,我希望程序跳过一行。

我有一个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' 

接着,我要通过这些行中的for循环,其迭代(见下面的代码)

# 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)

由于提前

+0

'其他:pass'是完全没有意义的,你应该离开它。 –

+3

'test_run_type_value ='3'' against'test_run_type_value == 3' – PRMoureu

回答

-1
test_run_type_value = '1' 

这设置test_run_type_value字符串'1'

if test_run_type_value == 1 … 

此相比test_run_type_value整数1

所以你基本上是比较字符串和整数这里,和那些从不等于:

>>> '1' == 1 
False 

您是否想使用字符串或整数这样的决定。例如。如果你分配1,它应该工作正常:

test_run_type_value = 1 # no quotes => int! 

Btw。你不必这样做:

else: 
    pass 

只是不包括别的,什么都不会做,如果条件是不正确的:

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