五月综合缴情婷婷六月,色94色欧美sute亚洲线路二,日韩制服国产精品一区,色噜噜一区二区三区,香港三级午夜理伦三级三

您現(xiàn)在的位置: 365建站網(wǎng) > 365文章 > Python for 循環(huán)語句用法詳解

Python for 循環(huán)語句用法詳解

文章來源:365jz.com     點(diǎn)擊數(shù):613    更新時(shí)間:2017-12-25 09:22   參與評(píng)論
Python for循環(huán)可以遍歷任何序列的項(xiàng)目,如一個(gè)列表或者一個(gè)字符串。
語法:
for循環(huán)的語法格式如下:

for iterating_var in sequence:
   statements(s)

流程圖:

 


實(shí)例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for letter in 'Python':     # 第一個(gè)實(shí)例
   print '當(dāng)前字母 :', letter

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二個(gè)實(shí)例
   print '當(dāng)前水果 :', fruit

print "Good bye!"


以上實(shí)例輸出結(jié)果:

當(dāng)前字母 : P
當(dāng)前字母 : y
當(dāng)前字母 : t
當(dāng)前字母 : h
當(dāng)前字母 : o
當(dāng)前字母 : n
當(dāng)前水果 : banana
當(dāng)前水果 : apple
當(dāng)前水果 : mango
Good bye!


通過序列索引迭代

另外一種執(zhí)行循環(huán)的遍歷方式是通過索引,如下實(shí)例:
實(shí)例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print '當(dāng)前水果 :', fruits[index]

print "Good bye!"

以上實(shí)例輸出結(jié)果:

當(dāng)前水果 : banana
當(dāng)前水果 : apple
當(dāng)前水果 : mango
Good bye!

以上實(shí)例我們使用了內(nèi)置函數(shù) len() 和 range(),函數(shù) len() 返回列表的長度,即元素的個(gè)數(shù)。 range返回一個(gè)序列的數(shù)。

循環(huán)使用 else 語句

在 python 中,for … else 表示這樣的意思,for 中的語句和普通的沒有區(qū)別,else 中的語句會(huì)在循環(huán)正常執(zhí)行完(即 for 不是通過 break 跳出而中斷的)的情況下執(zhí)行,while … else 也是一樣。
實(shí)例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for num in range(10,20):  # 迭代 10 到 20 之間的數(shù)字
   for i in range(2,num): # 根據(jù)因子迭代
      if num%i == 0:      # 確定第一個(gè)因子
         j=num/i          # 計(jì)算第二個(gè)因子
         print '%d 等于 %d * %d' % (num,i,j)
         break            # 跳出當(dāng)前循環(huán)
   else:                  # 循環(huán)的 else 部分
      print num, '是一個(gè)質(zhì)數(shù)'


以上實(shí)例輸出結(jié)果:

10 等于 2 * 5
11 是一個(gè)質(zhì)數(shù)
12 等于 2 * 6
13 是一個(gè)質(zhì)數(shù)
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一個(gè)質(zhì)數(shù)
18 等于 2 * 9
19 是一個(gè)質(zhì)數(shù)



使用內(nèi)置 enumerate 函數(shù)進(jìn)行遍歷:

for index, item in enumerate(sequence):
    process(index, item)

實(shí)例

>>> sequence = [12, 34, 34, 23, 45, 76, 89]
>>> for i, j in enumerate(sequence):
...     print i,j
...
0 12
1 34
2 34
3 23
4 45
5 76
6 89

使用list.append()模塊對(duì)質(zhì)數(shù)進(jìn)行輸出。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 輸出 2 到 100 簡(jiǎn)的質(zhì)數(shù)
prime = []
for num in range(2,100):  # 迭代 2 到 100 之間的數(shù)字
   for i in range(2,num): # 根據(jù)因子迭代
      if num%i == 0:      # 確定第一個(gè)因子
         break            # 跳出當(dāng)前循環(huán)
   else:                  # 循環(huán)的 else 部分
      prime.append(num)
print prime

輸出結(jié)果:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

打印空心等邊三角形:
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打印空心等邊三角形

rows = int(raw_input('輸入行數(shù):'))
for i in range(0, rows):
    for k in range(0, 2 * rows - 1):
        if (i != rows - 1) and (k == rows - i - 1 or k == rows + i - 1):
            print " * ",
        elif i == rows - 1:
            if k % 2 == 0:
                print " * ",
            else:
                print "   ",
        else:
            print "   ",
    print "\n"


打印1-9三角形陣列:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for i in range(1,11):
    for k in range(1,i):
        print k,
        k +=1
    i +=1
    print "\n"

輸出結(jié)果:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

1 2 3 4 5 6

1 2 3 4 5 6 7

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7 8 9 


Python中for循環(huán)搭配else的陷阱
假設(shè)有如下代碼:

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

你期望的結(jié)果是,當(dāng)找到5時(shí)打印出:

found it! i = 5

實(shí)際上打印出來的結(jié)果為:

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

顯然這不是我們期望的結(jié)果。

根據(jù)官方文檔說法:

>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
大意是說當(dāng)?shù)膶?duì)象迭代完并為空時(shí),位于else的子句將執(zhí)行,而如果在for循環(huán)中含有break時(shí)則直接終止循環(huán),并不會(huì)執(zhí)行else子句。

所以正確的寫法應(yīng)該為:

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

當(dāng)使用pylint檢測(cè)代碼時(shí)會(huì)提示 Else clause on loop without a break statement (useless-else-on-loop)

所以養(yǎng)成使用pylint檢測(cè)代碼的習(xí)慣還是很有必要的,像這種邏輯錯(cuò)誤不注意點(diǎn)還是很難發(fā)現(xiàn)的


如對(duì)本文有疑問,請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答??! 點(diǎn)擊進(jìn)入論壇

發(fā)表評(píng)論 (613人查看0條評(píng)論)
請(qǐng)自覺遵守互聯(lián)網(wǎng)相關(guān)的政策法規(guī),嚴(yán)禁發(fā)布色情、暴力、反動(dòng)的言論。
昵稱:
最新評(píng)論
------分隔線----------------------------

其它欄目

· 建站教程
· 365學(xué)習(xí)

業(yè)務(wù)咨詢

· 技術(shù)支持
· 服務(wù)時(shí)間:9:00-18:00
365建站網(wǎng)二維碼

Powered by 365建站網(wǎng) RSS地圖 HTML地圖

copyright © 2013-2024 版權(quán)所有 鄂ICP備17013400號(hào)