# 详解python中for循环的使用方法

for循环在python中有遍历所有序列的项目，如列表或一个字符串。

for循环语法如下：

for iterating_var in sequence:
statements(s)

#!/usr/bin/python
for letter in ‘python’: # first example
print ‘current letter :’, letter
fruits = [‘banana’, ‘apple’, ‘mango’]
for fruit in fruits: # second example
print ‘current fruit :’, fruit
print “good bye!”

current letter : p
current letter : y
current letter : t
current letter : h
current letter : o
current letter : n
current fruit : banana
current fruit : apple
current fruit : mango
good bye!

#!/usr/bin/python
fruits = [‘banana’, ‘apple’, ‘mango’]
for index in range(len(fruits)):
print ‘current fruit :’, fruits[index]
print “good bye!”

current fruit : banana
current fruit : apple
current fruit : mango
good bye!

python支持与循环语句相关联的else语句。

#!/usr/bin/python
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print ‘%d equals %d * %d’ % (num,i,j)
break #to move to the next number, the #first for
else: # else part of the loop
print num, ‘is a prime number’

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

Posted in 未分类