一、while循環
例1
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
運作結果:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
例2 (while…else句式)
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
運作結果:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
二、for循環
例3
# -*- 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
目前水果 : mango
Good bye!
三、Pass語句
例4
# -*- coding: UTF-8 -*-
# 輸出 Python 的每個字母
for letter in 'Python':
if letter == 'h':
pass
print '這是 pass 塊'
print '目前字母 :', letter
print "Good bye!"
運作結果:
目前字母 : P
目前字母 : y
目前字母 : t
這是 pass
更多内容請關注微信公衆号