1. 程式人生 > >Python基礎教程之第5章 條件, 循環和其它語句

Python基礎教程之第5章 條件, 循環和其它語句

like eba cti python基礎 word 沒有 positive while循環 pytho

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
#Chapter 5 條件, 循環和其它語句
#5.1 print和import的很多其它信息
#對於非常多應用程序來說, 使用logging模塊記日誌比print語句更合適
#5.1.1 使用逗號輸出
#能夠看到, 每隔參數之間都自己主動插入了一個空格符
>>> print ‘Age:‘,42
Age: 42
>>> 1,2,3
(1, 2, 3)
#print的參數並不像我們預期那樣構成一個元組
>>> print 1,2,3
1 2 3
>>> print (1,2,3)
(1, 2, 3)
>>> name=‘Gumby‘
>>> salution=‘Mr.‘
>>> greeting=‘Hello,‘
>>> print greeting, salution, name
Hello, Mr. Gumby
>>> greeting=‘Hello‘
>>> print greeting, ‘,‘, salution, name
Hello , Mr. Gumby
>>> print greeting + ‘,‘, salution, name
Hello, Mr. Gumby
#假設在結尾處加上逗號,那麽接下來的語句會與前一語句在同一行打印(僅僅在腳本中起作用,在交互式Python會話中無效)
print ‘Hello,‘,
print ‘world!‘
#輸出Hello, world!
#5.1.2 import語句
#import somemodule
#from somemodule import somefunction
#from somemodule import somefunction, anotherfunction, yetanotherfunction
#from somemodule import *
#為模塊提供別名
>>> 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 序列解包(sequence unpacking)
>>> x, y, z = 1, 2, 3
>>> print x, y, z
1 2 3
>>> x, y = y, x
>>> print x, y, z
2 1 3
>>> values = 1,2,3
>>> values
(1, 2, 3)
>>> x,y,z=values
>>> x
1
>>> y
2
>>> z
3
>>> scoundrel={‘name‘:‘Robin‘, ‘girlfriend‘:‘Marion‘}
>>> key, value = scoundrel.popitem()
>>> key
‘girlfriend‘
>>> value
‘Marion‘
>>> x,y,z = 1,2

Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    x,y,z = 1,2
ValueError: need more than 2 values to unpack
>>> x,y,z=1,2,3,4

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    x,y,z=1,2,3,4
ValueError: too many values to unpack
#Python 3.0 中有另外一個解包的特性
#a,b,rest*=[1,2,3,4]
#rest的結果將會是[3,4]
#5.2.2 鏈式賦值
#x=y=somefunction
#等效於
#y=somefunction
#x=y

#5.2.3 增量賦值(augmented assignment)
>>> x=2
>>> x += 1
>>> x *= 2
>>> x
6
>>> fnord = ‘foo‘
>>> fnord += ‘bar‘
>>> fnord *= 2
>>> fnord
‘foobarfoobar‘
#語句塊: 縮排的樂趣
#5.4 條件和條件語句
# False None 0 "" ‘‘ () [] {} 會被解釋器看做假
>>> True
True
>>> False
False
>>> True == 1
True
#標準的布爾值為False(0)和True(1)
>>> False == 0
True
>>> True + False + 42
43
#bool函數能夠用來(和list, str以及tuple相似)轉換其它值
>>> bool(‘I think, therefore I am‘)
True
>>> bool(42)
True
>>> bool(‘‘)
False
>>> bool(0)
False
>>> bool([])
False
>>> bool(())
False
>>> bool({})
False
#5.4.2 條件運行和if語句
>>> name = raw_input(‘What is your name?

‘) What is your name? Gumby >>> if name.endswith(‘Gumby‘): ... print ‘Hello, Mr. Gumby‘ ... Hello, Mr. Gumby #5.4.3 else子句 >>> name = raw_input(‘What is your name? ‘) What is your name?

Jon >>> if name.endswith(‘Gumby‘): ... print ‘Hello, Mr. Gumby‘ ... else: ... print ‘Hello, stranger‘ ... Hello, stranger #5.4.4 elif子句 >>> num = input(‘Enter a number: ‘) Enter a number: 0 >>> 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 zero #5.4.5 嵌套代碼塊 >>> name = raw_input(‘What is your name? ‘) What is your name? Mrs. Gumby >>> 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‘ ... Hello, Mrs. Gumby #鏈式比較運算 #比較對象的時候能夠使用內建的cmp函數 >>> age=10 >>> 0<age<100 True >>> age=-1 >>> 0<age<100 False #相等運算符 >>> "foo" == "foo" True >>> "foo" == "bar" False >>> "foo" = "foo" File "<stdin>", line 1 SyntaxError: can‘t assign to literal #同一性運算符 #避免將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 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 #in: 成員資格運算符 >>> name = raw_input(‘What is your name? ‘) What is your name?

Jonathan >>> if ‘s‘ in name: ... print ‘Your name contains the letter "s".‘ ... else: ... print ‘Your name does not contain the letter "s".‘ ... Your name does not contain the letter "s". >>> "alpha" < "beta" True >>> ‘FnOrd‘.lower() == ‘Fnord‘.lower() True >>> [1,2] < [2,1] True >>> [2,[1,4]]<[2,[1,5]] True #布爾運算符 >>> number = input(‘Enter a number between 1 and 10: ‘) Enter a number between 1 and 10: 8 >>> if number <= 10: ... if number >=1: ... print ‘Great!‘ ... else: ... print ‘Wrong!‘ ... else: ... print ‘Wrong!‘ ... Great! >>> number = input(‘Enter a number between 1 and 10: ‘) Enter a number between 1 and 10: 6 >>> if number <= 10 and number >= 1: ... print ‘Great!‘ ... else: ... print ‘Wrong!‘ ... Great! >>> number = input(‘Enter a number between 1 and 10: ‘) Enter a number between 1 and 10: 11 >>> if 1 <= number <= 10: ... print ‘Great!‘ ... else: ... print ‘Wrong!‘ ... Wrong! >>> name = raw_input(‘Please enter your name: ‘) or ‘<unknown>‘ Please enter your name: >>> name ‘<unknown>‘ #短路邏輯和條件表達式 #相似C和Java中的三元運算符 >>> name = ‘Jon‘if True else ‘Jack‘ >>> name ‘Jon‘ >>> name = ‘Jon‘if False else ‘Jack‘ >>> name ‘Jack‘ #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 ... 1 2 3 ... 100 >>> x 101 >>> name = ‘‘ >>> while not name: ... name = raw_input(‘Please enter your name: ‘) ... Please enter your name: Please enter your name: Please enter your name: Jon >>> print ‘Hello, %s!‘ % name Hello, Jon! >>> name = ‘‘ >>> while not name or name.isspace(): ... name = raw_input(‘Please enter your name: ‘) ... Please enter your name: Please enter your name: Please enter your name: Chan >>> print ‘Hello, %s!‘ % name Hello, Chan! >>> while not name.strip(): ... name = raw_input(‘Please enter your name: ‘) ... >>> name = ‘‘ >>> while not name.strip(): ... name = raw_input(‘Please enter your name: ‘) ... Please enter your name: Please enter your name: Please enter your name: Kingston >>> print ‘Hello, %s!‘ % name Hello, Kingston! #5.5.2 for循環 >>> words=[‘this‘, ‘is‘, ‘an‘, ‘ex‘, ‘parrot‘] >>> for word in words: ... print word ... this is an ex parrot >>> numbers = [0,1,2,3,4,5,6,7,8,9] >>> for number in numbers: ... print number ... 0 1 2 3 4 5 6 7 8 9 >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #假設能使用for循環,就盡量不用while循環 #當須要叠代一個巨大的序列時,xrange會比range更高效 >>> for number in range(1,5): ... print number ... 1 2 3 4 #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 kye, ‘corresponds to‘, value ... Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: name ‘kye‘ is not defined >>> 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 一些叠代工具 #並行叠代 >>> names = [‘anne‘, ‘beth‘, ‘george‘, ‘damon‘] >>> ages = [12, 45, 32, 102] >>> for in in range(len(names)): SyntaxError: invalid syntax >>> for i in range(len(names)): print names[i], ‘is‘, ages[i], ‘year old‘ anne is 12 year old beth is 45 year old george is 32 year old damon is 102 year old >>> for i in range(len(names)): print names[i], ‘is‘, ages[i], ‘years old‘ anne is 12 years old beth is 45 years old george is 32 years old damon is 102 years old >>> zip(names, ages) [(‘anne‘, 12), (‘beth‘, 45), (‘george‘, 32), (‘damon‘, 102)] >>> for name, age in zip(names, ages): print name, ‘is‘, age, ‘years old‘ anne is 12 years old beth is 45 years old george is 32 years old damon is 102 years old >>> zip(range(5), xrange(100000000)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] #在索引上叠代 >>> strings = [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘] >>> for string in strings: index = strings.index(string) # Search for the string in the list of strings strings[index]=‘[censored]‘ >>> strings [‘[censored]‘, ‘[censored]‘, ‘[censored]‘] >>> strings = [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘] >>> for string in strings: if ‘xxx‘in strings: index = strings.index(string) # Search for the string in the list of strings strings[index]=‘[censored]‘ >>> strings [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘] >>> strings = [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘] >>> for string in strings: if ‘xxx‘ in string: index = strings.index(string) # Search for the string in the list of strings strings[index]=‘[censored]‘ >>> >>> string ‘Say goodbye‘ >>> strings [‘[censored]‘, ‘I like losing my face‘, ‘Say goodbye‘] >>> [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘] [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘] >>> index = 0 >>> for string in strings: if ‘xxx‘ in string: strings[index]=‘[censored]‘ index += 1 SyntaxError: invalid syntax >>> index = 0 >>> for string in strings: if ‘xxx‘ in string: strings[index]=‘[censored]‘ index += 1 >>> strings [‘[censored]‘, ‘I like losing my face‘, ‘Say goodbye‘] >>> [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘, ‘xxx is a sensitive word‘] [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘, ‘xxx is a sensitive word‘] >>> for index, string in enumerate(strings): if ‘xxx‘ in string: strings[index]=‘[censored]‘ >>> strings [‘[censored]‘, ‘I like losing my face‘, ‘Say goodbye‘] >>> strings = [‘I am xxx‘, ‘I like losing my face‘, ‘Say goodbye‘, ‘xxx is a sensitive word‘] #enumerate函數能夠在提供索引的地方叠代索引-值對. >>> for index, string in enumerate(strings): if ‘xxx‘ in string: strings[index]=‘[censored]‘ >>> strings [‘[censored]‘, ‘I like losing my face‘, ‘Say goodbye‘, ‘[censored]‘] #翻轉和排序叠代 >>> sorted([4,3,6,8,3]) [3, 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 跳出循環 #break >>> from math import sqrt >>> for n in range(99, 0, -1); SyntaxError: invalid syntax >>> for n in range(99, 0, -1): root = sqrt(n) if root == int(root): print n break 81 # continue # while True/break習慣使用方法 >>> word = ‘dummy‘ >>> while word: word = raw_input(‘Please enter a word: ‘) # 處理word: print ‘The word was ‘ + word Please enter a word: first The word was first Please enter a word: second The word was second Please enter a word: The word was >>> word = raw_input(‘Please enter a word: ‘) Please enter a word: first >>> while word: print ‘The word was ‘ + word word = raw_input(‘Please enter a word: ‘) The word was first Please enter a word: second The word was second Please enter a word: >>> while True: word = raw_input(‘Please enter a word: ‘) if not word: break print ‘The word was ‘ + word Please enter a word: first The word was first Please enter a word: second The word was second Please enter a word: #5.5.6 循環中else子句 #原始方案 from math import sqrt break_out = False for n in range(99, 81, -1): root = sqrt(n) if root == int(root): break_out = True print n break if not break_out: print "Didn‘t find it!" #結果Didn‘t find it! #改進方案 from math import sqrt for n in range(99, 81, -1): root = sqrt(n) if root == int(root): print n break else: print "Didn‘t find it!" #結果Didn‘t find it! #列表推導式(list comprehension)--輕量級循環 >>> [x*x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] #能夠和if子句聯合使用 >>> [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)] >>> >>> result=[] >>> for x in range(3): for y in range(3): result.append((x,y)) >>> result [(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‘] >>> letterGirls={} >>> 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‘, ‘bob+bernice‘] >>> letterGirls {‘a‘: [‘alice‘], ‘c‘: [‘clarice‘], ‘b‘: [‘bernice‘]} #5.7 三人行 pass, del 和 exec #5.7.1 什麽都沒發生 >>> name = ‘Bill Gates‘ >>> if name == ‘Ralph Auldus Melish‘: ... print ‘Welcome!‘ ... elif name == ‘Enid‘: ... pass ... elif name == ‘Bill Gates‘: ... print ‘Access Denied‘ ... Access Denied #5.7.2 使用del刪除 >>> scoundrel = {‘age‘:42, ‘first name‘:‘Robin‘, ‘last name‘:‘of Locksley‘ >>> robin = scoundrel >>> scoundrel {‘last name‘: ‘of Locksley‘, ‘first name‘: ‘Robin‘, ‘age‘: 42} >>> robin {‘last name‘: ‘of Locksley‘, ‘first name‘: ‘Robin‘, ‘age‘: 42} >>> scoundrel = None >>> scoundrel >>> print scoundrel None >>> robin {‘last name‘: ‘of Locksley‘, ‘first name‘: ‘Robin‘, ‘age‘: 42} >>> x = 1 >>> y = x >>> 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‘] >>> del x >>> y [‘Hello‘, ‘Python‘] #5.7.3 使用exec和eval運行和求值字符串 # exec 在 Python 3.0 中是一個函數而不是語句 >>> exec "print ‘Hello, world!‘" Hello, world! >>> from math import sqrt >>> exec "sqrt=1" >>> sqrt(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ‘int‘ object is not callable #命名空間,或稱為作用域(scope) #能夠通過in <scope> 來實現, 當中的<scope>就是起到放置代碼字符串命名空間作用的字典 >>> from math import sqrt >>> scope={} >>> exec ‘sqrt = 1‘ in scope >>> sqrt(4) 2.0 >>> scope [‘sqrt‘] 1 >>> len(scope) 2 >>> scope.keys() [‘__builtins__‘, ‘sqrt‘] # eval--求值字符串 >>> eval(raw_input("Enter an arithmetic express: ")) Enter an arithmetic express: 6 + 18 * 2 42 >>> scope={} >>> scope[‘x‘]=2 >>> scope[‘y‘]=3 >>> eval(‘x * y‘, scope) 6 >>> scope = {} >>> exec ‘x=2‘ in scope >>> eval(‘x*x‘, scope) 4 >>> #5.8 小結 #打印--print語句能夠用來打印由逗號隔開的多個值. 假設語句以逗號結尾,隨後的print語句會在同一行內接續打印 #導入--能夠用as對模塊或函數提供別名 #賦值--通過 序列解包 和 鏈式賦值 功能, 多個變量能夠一次性賦值, 通過 增量賦值 能夠原地改變變量 #塊--塊是通過縮排使語句成組的一種方法. 塊能夠在條件以及循環語句中使用,也能夠在函數和類中使用 #條件--幾個條件能夠串聯使用if/elif/else. 另一個變體叫做條件表達式,形如a if b else c. #斷言--斷言簡單來說就是肯定某事(布爾表達式)為真, 也可在它後面跟上這麽覺得的原因. #循環--能夠使用continue語句跳過塊中的其它語句然後繼續下一次叠代, 或使用break語句跳出循環 # 還能夠選擇在循環結尾加上else子句, 當沒有運行循環內部的break語句時便會運行else子句中的內容. #列表推導式--是看起來像循環的表達式.通過它, 能夠從舊列表中產生新的列表, 對元素應用函數, 過濾掉不須要的元素,等等. #pass, del, exec 和 eval 語句. pass語句什麽都不做, 能夠作為占位符使用. del語句用來刪除變量(名稱),或數據結構的一部分, 可是不能用來刪除值. # exec語句用與運行Python程序同樣的方式來運行字符串. 內建的eval函數對字符串中的表達式進行求值並返回結果. #5.8.1 本章的新函數 #chr(n) 返回序數n所代表的字符的字符串(0<=n<=256) #eval(source[, globals[, locals]]) 將字符串作為表達式計算,而且返回值 #enumerate 產生用於叠代的(索引,值)對 #ord(c) 返回單字符字符串的int值 #range([start,] stop[, step]) 創建整數的列表 #reversed(seq) 產生seq中值的反向副本, 用於叠代 #sorted(seq[, cmp][, key][, reverse]) 返回seq中值排序後的列表副本 #xrange([start,] stop[, step]) 創建xrange對象用於叠代 #zip(seq1, seq2,...) 創建用於並行叠代的新序列


Python基礎教程之第5章 條件, 循環和其它語句