python循环语句

Python提供了for循环和while循环(在Python中没有do..while循环),其中break continue的作用跟C/C++ java中一样:
1. while 循环 在给定的判断条件为 true 时执行循环体,否则退出循环体。
2. for 循环 重复执行语句
3. 嵌套循环 你可以在while循环体中嵌套for循环
4. pass语句 空语句

*while循环

while 判断条件:
        执行语句……

实例:

下面实例跟C/C++ java其他的类似的语言的while循环类似,在语法格式上有稍微区别,也可以使用break continue关键字

count = 0
var = 0
while (var == 0):
    if(count == 2)
        continue
    if(count == 5)
        break
    print "current count = ", count
    count = count + 1
print "Python while done"

*循环使用 else 语句
在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,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 循环
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。同样的,for循环中也可以使用else语句,用法和运行轨迹跟while循环中使用else语句一样

语法:

for循环的语法格式如下:

for iterating_var in sequence:
   statements(s)
for letter in 'Python':  
   print 'Current Letter :', letter
else:
    print 'For letter in python done---normal'

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:      
   print 'Current fruit :', fruit

print "Good bye!"

这种操作类似C++中的迭代器使用方式,后面还有一种类似使用数组下标的操作,以上实例输出结果:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
For letter in python done---normal
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

类似数组下标使用方式:
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!

*嵌套循环
循环可以互相嵌套,for循环嵌套while,或者while中嵌套for
实例:

count = 0
for var in 'China':
    print 'Current char: ', var
    while(count == 0):
        print 'while in count = ', count
        count = count +1
else:
    print 'loop end'

以上实例输出:
Current char:  C
while in count =  0
Current char:  h
Current char:  i
Current char:  n
Current char:  a
loop end

*pass语句
Python pass是空语句,是为了保持程序结构的完整性。
passass 不做任何事情,一般用做占位语句。

for letter in 'Python':
   if letter == 'h':
      pass
      print 'this pass block'
   print 'current char :', letter

print "Good bye!"

以上实例输出:
current char : P
current char : y
current char : t
this pass block
current char : h
current char : o
current char : n
Good bye!

你可能感兴趣的:(Python)