1. 程式人生 > >Python中for迴圈搭配else的陷阱

Python中for迴圈搭配else的陷阱

假設有如下程式碼:

for i in range(10):
    if i == 5:
        print 'found it! i = %s' % i
else:
    print 'not found it ...'

你期望的結果是,當找到5時打印出:

found it! i = 5

實際上打印出來的結果為:

found it! i = 5
not found it ...

顯然這不是我們期望的結果。

根據官方文件說法:

>When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates.

>A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.

https://docs.python.org/2/reference/compound_stmts.html#the-for-statement

大意是說當迭代的物件迭代完併為空時,位於else的子句將執行,而如果在for迴圈中含有break時則直接終止迴圈,並不會執行else子句。

所以正確的寫法應該為:

for i in range(10):
    if i == 5:
        print 'found it! i = %s' % i
        break
else:
    print 'not found it ...'

當使用pylint檢測程式碼時會提示 Else clause on loop without a break statement (useless-else-on-loop)

所以養成使用pylint檢測程式碼的習慣還是很有必要的,像這種邏輯錯誤不注意點還是很難發現的。

唔~

相關推薦

Pythonfor迴圈搭配else陷阱

假設有如下程式碼: for i in range(10): if i == 5: print 'found it! i = %s' % i else: print 'not found it ...' 你期望的結果是,當找到5時打印出: found it! i = 5 實際上打

pythonfor迴圈常用方法

#【1】遍歷列表 languages=["c","c++","python","shell"] for x in languages:     print(x) #【2】使用內建range()函式遍歷數字序列 for j in range(5):  

python for迴圈(continue, break, pass)用法

1、continue  跳過當前繼續執行下一個迴圈 l = ['a','b','c','d','e'] for i in l: #i遍歷l列表中的每一個元素 if i == 'c': continue #continue以下的程式碼不執行直

pythonfor迴圈把字串或者字典新增到列表

python中如何for迴圈把字串新增到列表?例項:    1.單個字串用for迴圈新增到列表中:# 把L1中的字串新增到列表alist裡面 L1 = 'MJlifeBlog' alist = [] # 可以用forin來迭代L1並儲存值到x變數裡頭即可。 # 接著在for迴

pythonfor迴圈使用range、len、enumerate函式的操作例項

#coding=utf8 print ''' Python中的for迴圈更像shell腳本里的foreach迭代。 Python中的for接受可迭代物件作為其引數,每次迭代其中一個元素。 Pytho

pythonfor迴圈的小技巧

偶爾看到一個神奇的用法: [[row[i] for row in matrix] for i in range(4)] 這是幹嘛的?就是把一個矩陣轉制。。轉制。。轉制。。我擦那麼吊? 然後就呼叫了一部分試試,發現樂是這麼個意思: 當for語句再外面有個[  ]的時候。可以

Pythonfor循環搭配else陷阱

結果 陷阱 循環 python ... 找到 clas for循環 並不會 假設有如下代碼: for i in range(10): if i == 5: print ‘found it! i = %s‘ % i else: print ‘n

pythonfor......else......的使用

for x in range(5): if x == 2: print(x) # break else: print("執行else....")  上述程式碼:當缺少break關鍵字時,程式的執行結果是: 2 執行else....

pythonfor/else組合實現素數的輸出

在python中,else除去和if搭配使用外,還可以和try,for,while等搭配使用 下面僅以for/else為例說明: ""輸出1——200的素數""" import math sum=0 print("100-200的素數:") for i in range(

lambda表示式 Pythonfor迴圈的lambda

Python 之 for迴圈中的lambda 第一種 f = [lambda x: x*i for i in range(4)]  (如果將x換成i,呼叫時候就不用傳引數,結果都為3) 對於上面的表示式,呼叫結果: >>> f = [lambda x:

Python迴圈for和while

這裡,我們將使用for迴圈和while迴圈做一個小遊戲,猜大小 假設有一個數num,給他設定一個預設值,直到猜對為止 num=22#預設值 flag=False #判斷標準 while flag==False:#只要滿足條件,進入執行     var=int(input(

Python迴圈以及break/continue/else/pass

簡單記錄一下Python再次學習的所得...... While和For迴圈。 1、while。 結構: while 條件:     opts else:     opts 一個簡單的小例子: i = 0 while i < 10 : print i

pythonfor循環

for else1、打印0-9 十個數字 for i in range(10): print(i) 2、打印偶數: for i in range(0,10,2): print(i) 3、if判斷中猜遊戲,升級(只能猜三次,超過三次沒猜對,提示退出) _age = 18 f

Java和Pythonfor循環的比較

Java和Python中for循環的比較Java是強類型的語言,而python是弱類型的語言。先看Java中的for循環使用,如下圖: package test06; /* * for 循環的條件 * for (循環初始表達式;循環條件表達式;循環後的表達式) */ public class Fort

使用javafor迴圈迴圈打印出五角星--

//5.0 輸出五角星        int touHigh = 6;        int jianHigh = 25 ;       &

JSfor迴圈之斐波拉切數列-兔子問題

兔子問題: 有個人想知道,一年之內一對兔子能繁殖多少對?於是就築了一道圍牆把一對兔子關在裡面。已知一對兔子每個月可以生一對小兔子,而一對兔子從出生後第3個月起每月生一對小兔子。假如一年內沒有發生死亡現象,那麼,一對兔子一年內(12個月)能繁殖成多少對?(兔子的規律為數列,1,1,2,3,5,8,

在Javafor迴圈的++i與i++問題

###首先指出二者在用法上並無區別: 首先看一段程式碼: int i; for (i = 0, j = 0; i < 2, j < 2; i++, ++j) { printf("i = %d ", i); printf("j = %d\n"

python的try/except/else/finally語句

與其他語言相同,在python中,try/except語句主要是用於處理程式正常執行過程中出現的一些異常情況,如語法錯誤(python作為指令碼語言沒有編譯的環節,在執行過程中對語法進行檢測,出錯後發出異常訊息)、資料除零錯誤、從未定義的變數上取值等;而try/finally語句則主要用於在

pythonwhile迴圈運算子及格式化輸出

一,while迴圈 while 條件:       while語句塊(迴圈體) 執行: 判斷你給的條件是否為真,如果真則執行迴圈體。否則跳出迴圈。 執行完迴圈體之後再次判斷條件是否為真 例子1 我們玩聯盟的時候噴打野的的時候,可以用這種方式,這是一個死迴圈,條件

pythonfor迴圈、while迴圈

1、for迴圈使用之乘法表 for i in range(1,10): for j in range(1,i+1): print('%s * %s = %s '%(j,i,i*j),end='') print(end='\n')   2、while