《python基础教程》笔记之条件语句和循环语句

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

布尔变量下面的值会被解释器看做假(false):

False None 0 "" () {} []

其它的一切都被解释为真。

>>> True

True

>>> False

False

>>> True == 1

True

>>> False == 0

True

>>> True + False +42

43

bool函数 -- 用来转换其它值,如

>>> bool([])

False

>>> bool('hello,world')

True

条件语句if else elif

is 和 is not -- 判断两个变量是不是同一个对象

>>> x=y=[1,2,3]

>>> z=[1,2,3]

>>> x == y

True

>>> x == z

True

>>> x is y

True

>>> x is z

False

上例中可见,因为is运算符是判定同一性的。变量x和y都被绑定在同一个列表上,而变量z被绑定在另外一个具有相同数值和顺序的列表上。它们的值可能相同,但是却不是同一个对象。

in 和 not in -- 成员资格运算符

assert -- 当条件不为真时,程序崩溃

>>> x = 5

>>> assert 0<x<10

>>> assert 5<x <4

Traceback (most recent call last):

File "<pyshell#25>", line 1, in <module>

assert 5<x <4

AssertionError

循环range -- 内建范围函数,它包含下限,但不包含上限,如

>>> range(0,10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

fornuminrange(0, 10):PRintnum,

结果如下

>>>

0 1 2 3 4 5 6 7 8 9

循环遍历字典,可以使用序列解包,如

d = {'x':1,'y':2}forkey, valueind.items():printkey,'corresponds to', value

结果

>>>

y corresponds to 2

x corresponds to 1

zip-- 可以将任意多个序列“压缩”在一起,然后返回一个元组的列表,同时他可以应付不等长的序列,当最短的序列“用完”时就会停止,如

>>> zip(range(5), xrange(10000))

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

>>> names=['a', 'b', 'c']

>>> ages = [45, 23 ,98]

>>> zip(names, ages)

[('a', 45), ('b', 23), ('c', 98)]

并行迭代,如

names=['a','b','c']

ages= [45, 23 ,98]forname, ageinzip(names, ages):printname,'is', age,'old'

结果

>>>

a is 45 old

b is 23 old

c is 98 old

编号迭代 -- 迭代序列中的对象,同时还要获取当前对象的索引,如

names=['Mr.a','Ms.b','Mr.c']forindex, nameinenumerate(names):if'Mr'inname:

names[index]='nan'fornameinnames:printname,

结果

>>>

nan Ms.b nan

翻转和排序迭代(sorted和reversed) -- 作用域任何序列或可迭代对象上,不是原地修改对象,而是返回翻转或排序后的版本,但是返回对象不能直接对它使用索引、分片以及调用list方法,可以使用list类型转换返回的对象,如

>>> sorted([4,3,8,6,3,])

[3, 3, 4, 6, 8]

>>> sorted('hello, world!')

[' ', '!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

>>> list(reversed('hello, world!'))

['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'h']

>>> ''.join(reversed('hello, world!'))

'!dlrow ,olleh'

break/continue -- 跳出循环/继续下一轮循环

循环中的else子句 -- 如果循环中没有调用break时,else子句执行,如

frommathimportsqrtforninrange(99, 81, -1):

root=sqrt(n)ifroot ==int(root):printn

breakelse:print"Didn't dind it!"

结果

>>>

Didn't dind it!

列表推导式--轻量级循环列表推导式是利用其它列表创建新列表的一种方法,如

>>> [(x,y) for x in range(3) for y in range(3)]

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

>>> girls = ['alice', 'bernice', 'clarice']

>>> boys = ['chris', 'arnold', 'bob']

>>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]

['chris+clarice', 'arnold+alice', 'bob+bernice']

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航