2017-08-02 251 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