1. 程式人生 > >讀書筆記--《Python基礎教程第二版》-- 第五章 條件、循環和其他語句

讀書筆記--《Python基礎教程第二版》-- 第五章 條件、循環和其他語句

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基礎教程第二版》-- 第五章 條件、循環和其他語句