Python for 循環語句的使用
Python for循環可以遍歷任何序列的項目,如一個列表或者一個字符串。
語法:
for循環的語法格式如下:
for iterating_var in sequence: statements(s)
#!/usr/bin/python# -*- coding: UTF-8 -*- for letter in ’Python’: # 第一個實例 print ’當前字母 :’, letter fruits = [’banana’, ’apple’, ’mango’]for fruit in fruits:# 第二個實例 print ’當前水果 :’, fruit print 'Good bye!'
以上實例輸出結果:
當前字母 : P當前字母 : y當前字母 : t當前字母 : h當前字母 : o當前字母 : n當前水果 : banana當前水果 : apple當前水果 : mangoGood bye!
通過序列索引迭代另外一種執行循環的遍歷方式是通過索引,如下實例:
實例
#!/usr/bin/python# -*- coding: UTF-8 -*-fruits = [’banana’, ’apple’, ’mango’]for index in range(len(fruits)): print ’當前水果 :’, fruits[index]print 'Good bye!'以上實例輸出結果:
當前水果 : banana
當前水果 : apple
當前水果 : mango
Good bye!
以上實例我們使用了內置函數 len() 和 range(),函數 len() 返回列表的長度,即元素的個數。 range返回一個序列的數。
循環使用 else 語句在 python 中,for … else 表示這樣的意思,for 中的語句和普通的沒有區別,else 中的語句會在循環正常執行完(即 for 不是通過 break 跳出而中斷的)的情況下執行,while … else 也是一樣。
實例
#!/usr/bin/python# -*- coding: UTF-8 -*- for num in range(10,20): # 迭代 10 到 20 之間的數字 for i in range(2,num): # 根據因子迭代 if num%i == 0: # 確定第一個因子 j=num/i # 計算第二個因子 print ’%d 等于 %d * %d’ % (num,i,j) break # 跳出當前循環 else: # 循環的 else 部分 print num, ’是一個質數’
以上實例輸出結果:
10 等于 2 * 5
11 是一個質數
12 等于 2 * 6
13 是一個質數
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一個質數
18 等于 2 * 9
19 是一個質數
到此這篇關于Python for 循環語句的使用的文章就介紹到這了,更多相關Python for 循環語句內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: