标签:ja
5.1 print和import的更多信息
5.1.1 使用独号输出
>>> print ‘Age:‘,42
Age: 42
>>> 1,2,3
(1, 2, 3)
>>> print 1,2,3
1 2 3
>>> print (1,2,3)
(1, 2, 3)
>>> name=‘Gumby‘
>>> greeting=‘Hello‘
>>> salutation=‘Mr.‘
>>> print greeting ,salutation,name
Hello Mr. Gumby
>>> print greeting ,‘,‘,salutation,name
Hello , Mr. Gumby
>>> print greeting+‘,‘,salutation,name
Hello, Mr. Gumby
>>> print ‘Hello‘, # 在结尾处加独号,会打印在同一行
>>> print ‘World‘
Hello World
5.1.2 把某件事作为另一件事导入
import somemodule
from somemodule import somefunction
from somemodule import somefunction,anotherfunction
from somemodule import *
多个模块有同样的函数
module1.open()
module2.open()
>>> import math as foobar
>>> foobar.sqrt(4)
2.0
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
from module1 import open as open1
from module2 import open as open2
5.2 赋值魔法
5.2.1 序列解包,将多个值的序列解开,然后放到变量的序列中,序列解包要解开的值和赋值的值的数量完全一致
>>> print x,y,z
1 2 3
>>> x,y=y,x
>>> print x,y,z
2 1 3
>>> scoundrel={‘name‘:‘Robin‘,‘girlfried‘:‘Marion‘}
>>> key,value=scoundrel.popitem()
>>> key
‘girlfried‘
>>> value
5.2.2 链式赋值
x=y=somefunction()
等价于:
y=somefunction()
x=y
注意上面的语句和下面的语句不一定等价:
x=somefunction()
y=somefunction()
5.2.2 增量赋值
>>> x=2
>>> x+=1
>>> x*=2
>>> x
6
>>> fnord=‘foo‘
>>> fnord +=‘bar‘
>>> fnord*=2
>>> fnord
5.3 语句块:缩排的乐趣
语句块是在条件为真时执行,或者执行多次的一组语句,语句块用:开始,块中每一条语句都有相同的缩进
5.4 条件和条件语句
5.4.1 这就是布尔变量的作用
下面的值作为布尔表示试的时候,会被解释器看做假
False、None、0,()、"" ,(),[],{}
True,出去上面为空的,其他的一切都为真
True和Flase只不过是1和0的华丽说法而已
>>> True
True
>>> False
False
>>> True==1
True
>>> False==0
True
>>> True+False+42
43
所有的值都可以用做布尔值,所以不需要对它们进行显示转换
>>> bool(‘I think.therefore I am‘)
True
>>> bool(43)
True
>>> bool(‘‘)
False
>>> bool
>>> []!=""
True
5.4.2 条件执行和if语句
>>> name="Gumby"
>>> if name.endswith(‘Gumby‘):
... print ‘Hello,Mr.Gumby‘
...
Hello,Mr.Gumby
5.4.3 else 子句
>>> name="Gumby"
>>> if name.endswith(‘Gumby‘):
... print ‘Hello,Mr.Gumby‘
... else:
... print ‘Hello,stranger‘
...
Hello,Mr.Gumby
5.4.4 elif 子句
>>> num=input(‘Enter a number:‘)
Enter a number:4
>>> if num>0:
... print ‘The number is positive‘
... elif num<0:
... print ‘The number is negative‘
... else:
... print ‘The number is zero‘
...
The number is positive
5.4.5 嵌套代码块
#!/usr/bin/python
name=raw_input(‘What is your name?‘)
if name.endswith(‘Gumby‘):
if name.startswith(‘Mr.‘):
print ‘Hello,Mr.Gumby‘
elif name.startswith(‘Mrs.‘):
print ‘Hello,Mrs Gumby‘
else:
print ‘Hello,Gumby‘
else:
print ‘Hello,Stranger‘
5.4.6 更复杂的条件
1、比较运算符
x == y
x < y
x > y
x >= y
x <= y
x != y
x is y x和y是同一对象
x is not y
x in y
x not in y
0<age<100 几个运算符可以连在一起
2、相等运算符
>>> ‘foo‘==‘foo‘
True
>>> ‘foo‘==‘bar‘
False
3、is:同一性运算符
>>> x = y = [1,2,3]
>>> z=[1,2,3]
>>> x==y
True
>>> x==z
True
>>> x is y
True
>>> x is z
False
>>> x = [1,2,3]
>>> y=[2,4]
>>> x is not y
True
>>> del x[2]
>>> y[1]=1
>>> y.reverse()
>>> x==y
True
>>> x is y
False
尽量将is运算符比较类似数值和字符串这类不可变值
4、in:成员资格运算符
>>> name="allen"
>>> if ‘s‘ in name:
... print ‘Your name contains the letter "s"‘
... else:
... print ‘Your name dose not contains the letter "s"‘
...
Your name dose not contains the letter "s"
5、字符串和序列比较
>>> "alpha" <‘beta‘
True
>>> ord(‘a‘)
97
>>> ord(‘b‘)
98
>>> chr(97)
‘a‘
>>> chr(98)
‘b‘
>>> ‘FnOrd‘.lower()==‘Fnord‘.lower()
True
>>> [1,2]<[2,1]
True
>>> [2,[1,4]] <[2,[1,5]]
True
6、布尔运算符 AND OR not
>>> number=20
>>> if number <=10 and number>=1:
... print ‘Great!‘
... else:
... print ‘Wrong!‘
...
Wrong
利用短路的特性
name=raw_input(‘Please enter your name:‘) or ‘<unkown>‘
a if b else c 如果b为真,返回a,否则返回c
5.4.7 断言
>>> age =10
>>> assert 0<age<100
>>> age = -1
>>> assert 0<age<100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> age = -1
>>> assert 0<age<100 , ‘The age must be realistic‘
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: The age must be realistic
5.5 循环
5.5.1 while循环
>>> x =1
>>> while x <100:
... print x,
... x += 1
...
>>> name=‘‘
>>> while not name:
... name=raw_input(‘Please enter your name:‘)
... print ‘Hello,%s!‘ %name
while not name.strip()
while not name or name.isspace()
5.5.2 for循环,一般用来指定循环多次次
>>> words=[‘this‘,‘is‘,‘an‘,‘ex‘,‘parrot‘]
>>> for word in words:
... print word
...
this
is
an
ex
parrot
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for number in range(1,101):
... print number,
...
>>> xrange(1,10)
xrange(1, 10)
>>> for number in xrange(1,10):
... print number,
...
1 2 3 4 5 6 7 8 9
5.5.3 循环遍历字典元素
>>> d={‘x‘:1,‘y‘:2,‘z‘:3}
>>> for key in d:
... print key,‘corresponds to‘,d[key]
...
y corresponds to 2
x corresponds to 1
z corresponds to 3
>>> for key,value in d.items():
... print key,‘corresponds to‘,value
...
y corresponds to 2
x corresponds to 1
z corresponds to 3
5.5.4 一些迭代的工具
1、并行迭代
>>> names=[‘name‘,‘beth‘,‘damon‘]
>>> ages=[12,24,34]
>>> for i in range(len(names)):
... print names[i],‘is‘,ages[i],‘years old‘
...
name is 12 years old
beth is 24 years old
damon is 34 years old
>>> zip(names,ages)
[(‘name‘, 12), (‘beth‘, 24), (‘damon‘, 34)]
>>> for name,age in zip(names,ages):
... print name, ‘is‘ ,age,‘years old‘
...
name is 12 years old
beth is 24 years old
damon is 34 years old
zip可以应付不等长序列
>>> zip(range(5),xrange(100000),range(4))
[(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 3)]
2、编号迭代
>>> l=[‘a‘,‘b‘,‘c‘]
>>> for index,value in enumerate(l):
... print index,‘is‘,value
...
0 is a
1 is b
3、翻转和排序迭代
reversed和sorted函数,作用于任何序列和可迭代对象上
>>> sorted([4,2,6,8,3])
[2, 3, 4, 6, 8]
>>> sorted(‘Hello,world!‘)
[‘!‘, ‘,‘, ‘H‘, ‘d‘, ‘e‘, ‘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‘
5.5.5 跳出循环
1、break
>>> for n in range(99,0,-1):
... root=sqrt(n)
... if root==int(root):
... print n
... break
...
81
2、continue
>>> range(0,10,2)
[0, 2, 4, 6, 8]
2、continue
for x in seq:
if condition1:continue
if condition2:continue
if condition3:continue
do_someting()
等价:
for x in seq:
if not (condition1 or condition2 or condition3):
do_someting()
3、while True/break
>>> while True:
... word=raw_input(‘Please enter a word:‘)
... if not word:break
... print ‘The word was‘+ word
...
Please enter a word:hello
The word washello
Please enter a word:nihao
The word wasnihao
Please enter a word:
替代下面的写法
>>> word=‘dumy‘
>>> while word:
... word=raw_input(‘Please enter a word:‘)
... print ‘The word was ‘+ word
...
Please enter a word:hello
The word was hello
Please enter a word:nihao
The word was nihao
Please enter a word:
The word was
5.5.6 循环中的else子句 ,在没有调用break的时候执行
#!/usr/bin/python
from math import sqrt
for n in range(99,80,-1):
root=sqrt(n)
if root==int(root):
print n
break
else:
print "didn‘t find it"
for while 循环中都可以使用break,continue,else子句
5.6 列表推导式 - 轻量级循环
利用其它列表创建新的列表
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x % 3 ==0]
[0, 9, 36, 81]
>>> [(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‘]
更优的方案:
>>> girls=[‘alice‘,‘bernice‘,‘clarice‘]
>>> boys=[‘chris‘,‘arnold‘,‘bob‘]
>>> for girl in girls:
... letterGirls.setdefault(girl[0],[]).append(girl)
...
>>> print letterGirls
{‘a‘: [‘alice‘], ‘c‘: [‘clarice‘], ‘b‘: [‘bernice‘]}
>>> for girl in girls:
... letterGirls.setdefault(girl[0],[]).append(girl)
... print [b+‘+‘+g for b in boys for g in letterGirls[b[0]]]
...
[‘chris+clarice‘, ‘arnold+alice‘, ‘arnold+alice‘, ‘bob+bernice‘]
[‘chris+clarice‘, ‘arnold+alice‘, ‘arnold+alice‘, ‘bob+bernice‘, ‘bob+bernice‘]
[‘chris+clarice‘, ‘chris+clarice‘, ‘arnold+alice‘, ‘arnold+alice‘, ‘bob+bernice‘, ‘bob+bernice‘]
5.7 三人行
5.7.1 什么都没有发生
>>> pass
#!/usr/bin/python
name=‘Ralap‘
if name==‘Ralap‘:
print ‘Welcome‘
elif name==‘End‘:
# not end
pass
elif name ==‘Bill‘:
print ‘Accedd Denied‘
5.7.2 使用del删除
del 删除的只是引用名,并不删除内存中的值,值由python自动回收
方法一:
>>> scoudrel={‘age‘:42,‘first name‘:‘Robin‘}
>>> robin=scoudrel
>>> robin
{‘first name‘: ‘Robin‘, ‘age‘: 42}
>>> scoudrel=None
>>> robin
{‘first name‘: ‘Robin‘, ‘age‘: 42}
>>> scoudrel
>>> robin=None
方法二:
>>> x = 1
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘x‘ is not defined
>>> x=["Hello","world"]
>>> y=x
>>> y[1]=‘Python‘
>>> x
[‘Hello‘, ‘Python‘]
>>> y
[‘Hello‘, ‘Python‘]
>>> del x
>>> y
[‘Hello‘, ‘Python‘]
5.7.3 使用exec和eval 执行和求值字符串
exec 执行一系列的python语句
>>> exec "print ‘Hello,World!‘"
Hello,World!
不能简单使用exec,这样并不安全
>>> from math import sqrt
>>> scope={}
>>> exec ‘sqrt=1‘ in scope
>>> sqrt(4)
2.0
>>> scope[‘sqrt‘]
1
>>> scope.keys()
[‘__builtins__‘, ‘sqrt‘]
eval 会计算python表达式,并返回结果值
>>> eval(‘6+18*2‘)
42
给exe和eval语句提供命名空间时,还可以在命名空间中放置一些值进去
>>> scope={}
>>> scope[‘x‘]=2
>>> scope[‘y‘]=3
>>> eval(‘x*y‘,scope)
6
>>> scope={}
>>> exec ‘x=2‘ in scope
>>> eval(‘x*x‘,scope)
4
本文出自 “小鱼的博客” 博客,谢绝转载!
读书笔记--《Python基础教程第二版》-- 第五章 条件、循环和其他语句
标签:ja
原文地址:http://395469372.blog.51cto.com/1150982/1963777