網站首頁 學習教育 IT科技 金融知識 旅遊規劃 生活小知識 家鄉美食 養生小知識 健身運動 美容百科 遊戲知識 綜合知識
當前位置:趣知科普吧 > IT科技 > 

for|python

欄目: IT科技 / 發佈於: / 人氣:2.08W

for是屬於python下的循環語句,它能夠遍歷任何序列的項目,比如一個列表或是一個字元串。

for循環的語法格式爲:

for iterating_var in sequence:   statements(s)

說明:在python中,for經常會與else一起出現,for中的語句其實與普通的沒有區別,而else中的語句會在循環正常執行完的情況下執行,也就是說for並不是透過break跳出而中斷的。

python for

參考範例:

1、

輸入代碼:

#!/usr/bin/python# -*- coding: UTF-8 -*- for letter in 'Python':     # 第一個實例   print("當前字母: %s" % letter) fruits = ['banana', 'apple',  'mango']for fruit in fruits:        # 第二個實例   print ('當前水果: %s'% fruit) print ("Good bye!")

輸出結果:

當前字母: P當前字母: y當前字母: t當前字母: h當前字母: o當前字母: n當前水果: banana當前水果: apple當前水果: mangoGood bye!

python for 第2張

2、

當然也可以透過序列索引迭代,具體代碼如下:

#!/usr/bin/python# -*- coding: UTF-8 -*- fruits = ['banana', 'apple',  'mango']for index in range(len(fruits)):   print ('當前水果 : %s' % fruits[index]) print ("Good bye!")

輸出結果:

當前水果 : banana當前水果 : apple當前水果 : mangoGood bye!
Tags:Python