
上QQ阅读APP看书,第一时间看更新
4.3 循环语句
顾名思义,循环语句就是将一个代码块执行多次的语法结构。如果想要打印一个数组,可以遍历数组中的每一个元素,然后打印出来,当遍历完整个数组时循环结束。也可以使用break关键字在循环过程中退出循环,或者使用continue关键字跳过其中的一次循环。
4.3.1 for循环语句
for循环的语法结构如下:
for x in s: statements
在这个例子中,s是一个包含多个元素的序列,如字符串、数组等。每一次遍历都会从s中提取一个元素并赋值给变量x,同时执行代码块。
例如,遍历数组并将数组的每一个元素乘以10打印出来:

输出结果:
>>> 10 >>> 20 >>> 30 >>> 40 >>> 50
使用continue语句可以跳过部分循环,如果只希望打印奇数数字,可以嵌套if语句,代码如下:

输出结果:
>>> 1 >>> 3 >>> 5
与continue不同的是,使用break语句可以跳出整个循环,后面所有的变量都不会继续执行,例如,只想打印出小于等于3的数字:

输出结果:
>>> 1 >>> 2 >>> 3
4.3.2 while循环语句
while循环的语法结构如下:

while循环会根据while判断条件决定是否执行内部代码,只有当判断条件为真时才能执行,否则循环结束。while循环也可以使用continue和break语句来控制循环执行。以while为例完成上面两个示例:
输出奇数:

输出结果:
>>> 1 >>> 3 >>> 5
输出小于等于3的数字:

输出结果:
>>> 1 >>> 2 >>> 3