Python循环语句是什么
一、循环语句介绍
一般情况下,需要多次重复执行的代码,都可以用循环的方式来完成。
循环不是必须要使用的,但是为了提高代码的重复使用率,所以有经验的开发者都会采用循环。
二、常见的循环形式
while循环
for循环
三、while循环
<pre class="brush:php;toolbar:false">while 条件: 满足条件时执行的代码1 满足条件时执行的代码2 ...(省略)...</pre>举例如下:
<pre class="brush:php;toolbar:false">i = 0 while i<5: print("i现在等于%d"%i) i =1</pre>运行结果为:
<pre class="brush:php;toolbar:false">i现在等于0 i现在等于1 i现在等于2 i现在等于3 i现在等于4</pre>while循环的嵌套
类似if的嵌套,while嵌套就是:while里面还有while。
<pre class="brush:php;toolbar:false">while 条件1: 满足1时,执行的代码1 满足1时,执行的代码2 ...(省略)... while 条件2: 满足2时,执行的代码1 满足2时,执行的代码2</pre>这也就是所谓的双重循环,典型的案例:打印九九乘法表:
<pre class="brush:php;toolbar:false">i=1 while i<=9: j=1 while i>=j: print("%d*%d=%-2d"%(i,j,i*j),end=" ") j =1 print("\n") i =1</pre>运行结果如下:
<pre class="brush:php;toolbar:false">1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81</pre>解释说明
%-2d意思是占2个位置的整形。
因为python中的print默认end是”\n”,所以默认时换行的,这里我们只需要修改end属性就可以了设置结尾不换行了。
相关推荐:《Python视频教程》
四、for循环
在Python中 for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。
for循环的格式
<pre class="brush:php;toolbar:false">for 临时变量 in 集合容器: 满足循环执行的代码 else: 不满足循环时执行的代码</pre>其中:else可写可不写,根据需要自行决定。
<pre class="brush:php;toolbar:false">name = "Se7eN_HOU" for x in name: print(x)</pre>运行结果为:
<pre class="brush:php;toolbar:false">’S’ ’e’ ’7′ ’e’ ’N’ ’_’ ’H’ ’O’ ’U’</pre>for循环嵌套
for循环和while循环一样也可以嵌套,还以打印九九乘法表为例演示:
<pre class="brush:php;toolbar:false">for i in range(1,10): for j in range(1,10): print("%d*%d=%-2d"%(i,j,i*j),end=" ") if i==j: break print("\n")</pre>运行效果为:
<pre class="brush:php;toolbar:false">1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81</pre>说明:
range()一个随机函数、在()里面写上随机数的范围。
五、continue和break
使用场景,通常在循环中当做中断循环使用,例如我本来想做10次循环,但是到第5次的时候我就不想循环了,或者第5次不想循环了,后面4次继续循环就需要用到break和continue。
continue:跳出当前本次循环,后面的循环继续进行。
<pre class="brush:php;toolbar:false">i = 1 while i<=10: if i==5: i =1 continue print(i) i =1</pre>运行结果为:
<pre class="brush:php;toolbar:false">1 2 3 4 6 7 8 9 10</pre>当i等于5的时候进入if语句,只做了自加1,continue之后的就print没有执行,但是i等于6,7,8,9,10次的循环继续执行了,所以continue只是结束当前这一次循环,后面的循环继续执行。
break:结束当前所有的循环,不管后面还有几次都不执行了。
<pre class="brush:php;toolbar:false">i = 1 while i<=10: if i==5: i =1 break print(i) i =1</pre>运行结果为:
<pre class="brush:php;toolbar:false">1 2 3 4</pre>当i等于5的时候,进入if语句,执行了i =1,之后执行break代码,直接退出循环,所以后面的,6,7,8,9,10次都不会执行了。
相关推荐:
Python中的分支判断语句是什么
您可能感兴趣的文章:
python之流程控制语句
python的三种程序结构是什么
python循环语句怎么写
python怎么退出for循环
python怎么写有死循环的程序
Python中for循环语句和while循环语句有何不同
jquery $.each 和for怎么跳出循环终止本次循环
工作繁琐?试试Python循环语句(for循环篇)
python中如何退出for循环
python中for与while的区别是什么