python 迴圈語句

2021-10-01 04:16:29 字數 3189 閱讀 3716

迴圈的作用在於將一段**重複執行多次。

while :

python會迴圈執行,直到不滿足為止。

例如,計算數字01000000的和:

in [1]:

i = 0

total = 0

while i < 1000000:

total += i

i += 1

print total

499999500000
之前提到,空容器會被當成false,因此可以用while迴圈來讀取容器中的所有元素:

in [2]:

plays = set(['hamlet', 'macbeth', 'king lear'])

while plays:

play = plays.pop()

print 'perform', play

perform king lear

perform macbeth

perform hamlet

迴圈每次從plays中彈出乙個元素,一直到plays為空為止。

for in :

for迴圈會遍歷完中所有元素為止

in [3]:

plays = set(['hamlet', 'macbeth', 'king lear'])

for play in plays:

print 'perform', play

perform king lear

perform macbeth

perform hamlet

使用for迴圈時,注意盡量不要改變plays的值,否則可能會產生意想不到的結果。

之前的求和也可以通過for迴圈來實現:

in [4]:

total = 0

for i in range(100000):

total += i

print total

4999950000
然而這種寫法有乙個缺點:在迴圈前,它會生成乙個長度為100000的臨時列表。

生成列表的問題在於,會有一定的時間和記憶體消耗,當數字從100000變得更大時,時間和記憶體的消耗會更加明顯。

為了解決這個問題,我們可以使用xrange來代替range函式,其效果與range函式相同,但是xrange並不會一次性的產生所有的資料:

in [5]:

total = 0

for i in xrange(100000):

total += i

print total

4999950000
in [6]:

%timeit for i in xrange(1000000): i = i
10 loops, best of 3: 40.7 ms per loop
in [7]:

%timeit for i in range(1000000): i = i
10 loops, best of 3: 96.6 ms per loop
可以看出,xrange用時要比range少。

遇到continue的時候,程式會返回到迴圈的最開始重新執行。

例如在迴圈中忽略一些特定的值:

in [8]:

values = [7, 6, 4, 7, 19, 2, 1]

for i in values:

if i % 2 != 0:

# 忽略奇數

continue

print i/2

3

21

遇到break的時候,程式會跳出迴圈,不管迴圈條件是不是滿足:

in [9]:

command_list = ['start', 

'process',

'process',

'process',

'stop',

'start',

'process',

'stop']

while command_list:

command = command_list.pop(0)

if command == 'stop':

break

print(command)

start

process

process

process

在遇到第乙個'stop'之後,程式跳出迴圈。

if一樣,whilefor迴圈後面也可以跟著else語句,不過要和break一起連用。

不執行:

in [10]:

values = [7, 6, 4, 7, 19, 2, 1]

for x in values:

if x <= 10:

print 'found:', x

break

else:

print 'all values greater than 10'

found: 7
執行:

in [11]:

values = [11, 12, 13, 100]

for x in values:

if x <= 10:

print 'found:', x

break

else:

print 'all values greater than 10'

all values greater than 10

Python迴圈語句 for迴圈

說明 1 計次迴圈,一般應用在迴圈次數已知的情況下。通常適用於列舉或遍歷序列以及迭代物件中的元素。2 迭代變數用於儲存讀取的值。3 物件為要遍歷或迭代的物件,該物件可以是任何有序的序列物件,如字串 列表 元組等 迴圈體為一組被重複執行的語句。4 for迴圈語句可以迴圈數值 遍歷字串 列表 元組 集合...

Python迴圈語句

while迴圈 1.一般語法 while 控制條件 執行語句 2.迴圈型別 無限迴圈 while true 執行語句 計數迴圈 count 0 while count 10 print count count 1 3.range 內建函式,返回乙個列表 range start,end,step 不包...

Python迴圈語句

python提供了for迴圈和while迴圈,但沒有do.while迴圈。while 判斷條件 執行語句 執行語句可以是單個語句或語句塊。判斷條件可以是任何表示式,任何非零 或非空 null 的值均為true 當判斷條件假false時,迴圈結束。判斷條件 還可以是個常值,表示迴圈必定成立,迴圈將會無...