2016-01-23 140 views
-4

好吧,我不知道如何正確地問這個問題,但這裏是我想要做的事:打破for循環,而不是停止while循環

#connect to db and stuff 
check_against = [] #list of strings 
while row is not None: 
    if row == None: 
    break 
    for i in range(0,len(row)): 
    x = row[i] 
    try: 
     print str(x) 
    except: 
     pass 
    for z in check_against: 
     if z == x: 
     #change alternate_id 
    if x == "": 
     # Change insert_into and stuff 
     if alternate_id != 0: 
     for x in range(len(insert_into)): #Do SQL things 
      print "updating" + str(alternate_id) 
      sql = """UPDATE `table` SET `%s` = '%s' WHERE `table`.`id` = %s""" % (insert_into[x],check_against[x],str(alternate_id)) 
     try: 
     cursor.execute(sql) 
     db.commit() 
     except: 
     db.rollback() 
     break #This break breaks the while loop 
    row = cursor.fetchone() 

我怎樣才能讓破不破while循環但打破循環? 感謝您的幫助。

+3

這正是你的代碼已經做...其實你不能離開'while',因爲'x'永遠不會改變它。 – jonrsharpe

+0

我做錯了嗎?當我在實際代碼中使用它時,它會打破while循環。 – Tygran

+0

@Tygran,你能提供所有的代碼嗎?因爲它看起來像當前的實現打破了'for'循環,因爲你想 – pivanchy

回答

0

首先,你不需要這個部分:

while row is not None: 
    if row == None: 
     break 

這部分沒有任何意義,因爲如果該行是沒有的while循環將停止,因爲條件while row is not None,請刪除:

if row == None: 
    break 

您不需要此代碼。

第二部分:如果break傷了你的while環路,請格式化你的代碼在一個正確的方式,因爲當前的代碼看起來很奇怪

+0

我想我已經想通了。 break不會中斷while循環,但問題在於我使用相同的光標執行sql,因爲我從中獲取行。謝謝你的幫助。我好蠢。 – Tygran

+0

不客氣!問題是關於打破一個循環,我告訴如何解決這個問題 – pivanchy