while 循环

Python 中 while 语句的一般形式:

  1. while 判断条件(condition):
  2. 执行语句(statements)……
  1. #!/usr/bin/env python3
  2. n = 100
  3. sum = 0
  4. counter = 1
  5. while counter <= n:
  6. sum = sum + counter
  7. counter += 1
  8. print("1 到 %d 之和为: %d" % (n,sum))

无限循环

while 循环使用 else 语句

  1. while <expr>:
  2. <statement(s)>
  3. else:
  4. <additional_statement(s)>
  1. #!/usr/bin/python3
  2. count = 0
  3. while count < 5:
  4. print (count, " 小于 5")
  5. count = count + 1
  6. else:
  7. print (count, " 大于或等于 5")


for 语句:

格式:

  1. for <variable> in <sequence>:
  2. <statements>
  3. else:
  4. <statements>
  1. tmp =['a','b','c','d','e']
  2. for x in tmp:
  3. print(x)


range()函数

如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列

  1. for i in range(5):
  2. print(i)


pass 语句

pass 不做任何事情,一般用做占位语句,如下实例

  1. class MyEmptyClass:
  2. ... pass