1.while循环
while 判断条件:
执行语句……
(1) while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立。
(2)循环使用 else 语句
在 python 中,while … else 在循环条件为 false 时执行 else 语句块。
2.for循环
for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
(1)用法
for iterating_var in sequence:
statements(s)
(2)for迭代字典
d = {'x':1,'y':2} for key in d : print(key,'corresponds to',d[key]) print("items()方法:") for key,value in d.items(): print(key,'corresponds to',value)
运行结果:
x corresponds to 1 y corresponds to 2 items()方法: x corresponds to 1 y corresponds to 2
可以使用keys等字典方法来获取所有的键,也可以使用d.values来获取所有的值,也可使用d.items以元组的方式返回键-值对。
(3)循环使用 else 语句
在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。