python学习笔记-循环(while for)<6>

<h3>1.while循环</h3>
<h5>1.1 while基本形式:</h5>
<pre>
while 判断条件:
循环语句
</pre>

1.执行语句可以是单个语句或或语句块。
2.判断条件可以是任何表达式,任何非零或非空(null)的值为True。
3.当判断条件假Flase时,循环结束。
4.判断条件还可以是常值,表示循环必定成立

注:判断条件为真时执行后面的语句,直到条件为假时跳出循环。
:冒号是语法的一部分

<h5>1.2 while语句的基本组成:</h5>
1.break 结束while(没有break语句,条件为True循环会一直执行下去)
2.continue 跳出当前这次循环,但不结束while
3.else 结束 while以后执行(如果是break跳出循环就不会执行else子句)

注意:普通应用里,while一定要给一个结束条件,否则就是传说中的死循环

<pre>

– coding:utf-8 –

a = 1
while a < 5:
a += 1
print a,
输出:2 3 4 5
</pre>

<pre>
while a < 5:
a += 1
if a == 4:
break
print a,
输出:2 3
</pre>

<pre>
while a < 5:
a += 1
if a == 3:
continue
print a,
输出:2 4 5
</pre>

<pre>

– coding: utf-8 –

a = 1
list1 = []
while a < 100:
if a%2 == 0:
list1.append(a)
a += 1
if a == 50:
print ‘xxxxxx’
break
else:
print ‘hahahah’
print list1
输出:’xxxxxx’
</pre>

<h3>2. for循环</h3>
<h5>2.1 for语句的基本格式:</h5>
<pre>
for item in iterable:
statement(s)
</pre>

1.iterable:可迭代对象,列表、元组、字符串、字典
2.break和continue的用法与while语句是一样的
3.else 结束 for以后执行(如果是break跳出循环就不会执行else子句)

<h5>2.2 range 函数:</h5>
range()内置函数会返回一个整数列表(方便的用于for循环中)
<pre>

range(10) #一个参数 默认从0开始
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1,10) #两个参数 包含头部数据,末尾不包含
[1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1,10,2) #三个参数 头,尾,隔多少取值
[1, 3, 5, 7, 9]
</pre>

<h5>2.3 continue 在for 语句中的作用:</h5>
<pre>
for i in range(-2,3):
if i ==0:
continue
print 1.0/i,
输出:-0.5 -1.0 1.0 0.5
</pre>

<h5>2.4 for 语句例子:</h5>
<pre>
a = (‘x’,’y’,’z’)
for i in a:
print i,
输出:x y z
</pre>
<pre>
for i in range(5):
print i,
输出:0 1 2 3 4
</pre>
<pre>
a = {‘a’:’xyz’,’b’:’ijk’,’c’:’abc’}
for i in a:
print i,
输出:a c b
</pre>
1.在for循环中迭代字典时,变量会被依次设置成字典的每个键。字典是无序的,所以就会以不确定的顺序返回字典的键;
2.要得到字典的值时,可以使用values()方法,使用items()方法可以获得键值对
<pre>

dic = {‘name’:’jack’,’age’:18,’sex’:’male’}
dic
{‘age’: 18, ‘name’: ‘jack’, ‘sex’: ‘male’}
for i in dic:
print i
age
name
sex
for i in dic.values():
print i
18
jack
male
for i in dic.items():
print i
(‘age’, 18)
(‘name’, ‘jack’)
(‘sex’, ‘male’)
</pre>

<h5>2.4 for语句也可以用来作为循环的次数</h5>
<pre>
for i in range(n)
循环体
</pre>
<pre>

a = 1
for i in range(3):
print ‘第%s次循环’ %a
a+=1
第1次循环

第2次循环
第3次循环
</pre>

<h3>3. 控制语句:</h3>
1.break:break语句用来终止循环语句,即循环条件没有False条件或者学列还没被完全递归完,也会停止执行循环语句
2.continue:continue语句用来告诉Python跳出当前循环的剩余语句,然后继续进行下一轮循环
3.pass:pass语句是空语句,是为了保持程序结构的完整性,pass不做任何事情一般用做占位语句

    原文作者:Alisa168
    原文地址: https://www.jianshu.com/p/acbd473081ac
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞