IT科技

當前位置 /首頁/IT科技 > /列表

python中for循環

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

當前水果: mango

Good 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

當前水果 : mango

Good bye!

TAG標籤:Python #