Python 循环语句

| 分类 python  | 标签 python 

###Python 循环语句###

  1. Python提供了for循环和while循环(在Python中没有do..while循环)

  2. 循环使用 else 语句

    1. python 中,for else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while else 也是一样
    1. #!/usr/bin/python
    2. count = 0
    3. while count < 5:
    4. print count, " is less than 5"
    5. count = count + 1
    6. else:
    7. print count, " is not less than 5"
  3. Python for 循环语句

    Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

    for循环的语法格式如下:

    1. for iterating_var in sequence:
    2. statements(s)
    3. #!/usr/bin/python
    4. for letter in 'Python': # First Example
    5. print 'Current Letter :', letter
    6. fruits = ['banana', 'apple', 'mango']
    7. for fruit in fruits: # Second Example
    8. print 'Current fruit :', fruit
    9. print "Good bye!"

    通过序列索引迭代

    1. #!/usr/bin/python
    2. fruits = ['banana', 'apple', 'mango']
    3. for index in range(len(fruits)):
    4. print 'Current fruit :', fruits[index]
    5. print "Good bye!"
    6. 以上实例我们使用了内置函数 len() range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。s

    循环使用 else 语句

    1. #!/usr/bin/python
    2. for num in range(10,20): #to iterate between 10 to 20
    3. for i in range(2,num): #to iterate on the factors of the number
    4. if num%i == 0: #to determine the first factor
    5. j=num/i #to calculate the second factor
    6. print '%d equals %d * %d' % (num,i,j)
    7. break #to move to the next number, the #first FOR
    8. else: # else part of the loop
    9. print num, 'is a prime number'
  4. Python pass 语句

    1. python pass是空语句,是为了保持程序结构的完整性。

青春是一场大雨,即使感冒了,还盼回头再淋一次...image...微笑永远是一个人身上最好看的东西...


PREVIOUS     NEXT