第五章 條件、迴圈和其他語句
print和import的更多資訊
>>> print 'Age:',42Age: 42>>> print 'Age;';42Age;42>>> name = 'Gumby'>>> salutation = 'Mr'>>> greeting = 'Hello,'>>> print greeting,salutation,nameHello, Mr Gumby
>>> import math as foobar>>> foobar.sqrt(4)2.0>>> from math import sqrt as foobar>>> foobar(4)2.0
賦值魔法
>>> x,y,z = 1,2,3>>> print x,y,z1 2 3>>> x,y = y,x>>> print x,y,z2 1 3>>> values = 1,2,3>>> values(1, 2, 3)>>> x,y,z = values>>> x1>>> y2>>> >>> scoundrel = {'name':'Robin','girlfriend':'Marion'}>>> key,value = scoundrel.popitem()>>> key'girlfriend'>>> value'Marion'
鏈式賦值
>>> x = y = 1>>> x1>>> y1>>>
增量賦值
>>> x = 2>>> x += 1>>> x3>>> x *= 4>>> x12>>> fnord = 'foo'>>> fnord += 'bar'>>> fnord'foobar'>>> fnord *=2>>> fnord'foobarfoobar'>>>
語句塊:縮排的樂趣
條件和條件陳述式
>>> TrueTrue>>> FalseFalse>>> True == 1True>>> False == 0True>>> True + False + 4344>>> >>> bool('I think, therefore I am')True>>> bool(42)True>>> bool('')False>>> bool("")False>>> bool(0)False>>> bool([])False>>> bool({})False>>> bool(False)False>>> bool(None)False>>>
條件執行和if語句(if、elif、else)
name = raw_input('What is your name?')if name.endswith('Gumby'): print 'Hello, Mr.Gumby'
num = input('Enter a number:')if num > 0: print 'The number is positive'elif num < 0: print 'The number is negative'else: print 'The number is zero'
嵌套代碼塊
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'
更複雜的條件
比較子
>>> 'foo' == "foo"True>>> 'foo' == 'bar'False>>> x = y = [1,2,3]>>> z = [1,2,3]>>> x == yTrue>>> x is yTrue>>> x is zFalse>>> x = z>>> x ==zTrue>>> >>> x = [1,2,3]>>> y = [2,4]>>> x is not yTrue>>> del x[2]>>> x[1, 2]>>> y[1] = 1>>> y.reverse()>>> y[1, 2]>>> x == yTrue>>> x is yFalse
name = raw_input('What is your name?')if 's' in name: print 'Your name contains the letter "s".'else: print 'Your name doesn\'t 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:')if number <= 10 and number >= 1: print 'Great'else: print 'Wrong'
斷言
迴圈
while迴圈
x = 1while x <= 1000: print x x += 1
name = ''while not name: name = raw_input('Please enter your name?')print 'Hello, %s!' % name
for迴圈
words = ['this','is','an','ex','parrot']for word in words: print word
numbers = [0,1,2,3,4,5,6,7,8,9]for number in numbers: print number
>>> 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]>>>
d = {'x':1,'y':2,'z':3}for key in d: print key, 'corresponds to', d[key]
y corresponds to 2x corresponds to 1z corresponds to 3
一些迭代工具
names = ['anne','beth','george','damon']ages = [12,45,32,102]for i in range(len(names)): print names[i],'is',ages[i],'year old'
翻轉和排序迭代
>>> sorted([4,3,6,8,3])[3, 3, 4, 6, 8]>>> sorted('Hello, world!')[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
跳出迴圈
break
from math import sqrtfor n in range(99,0,-1): root = sqrt(n) if root == int(root): print n break
>>> range(0,10,2)[0, 2, 4, 6, 8]>>>
continue
while True/break
word = 'dummy'while word: word = raw_input('Please enter a word:') print 'The word was ' + word
word = raw_input('Please enter a word:')while word: print 'The word was ' + word word = raw_input('Please enter a word:')
while True: word = raw_input('Please enter a word:') if not word:break print 'The word was ' + word
from math import sqrtfor n in range(92,99,1): root = sqrt(n) if root == int(root): print n break else: print "Didn't find it!",n
Didn't find it! 92Didn't find it! 93Didn't find it! 94Didn't find it! 95Didn't find it! 96Didn't find it! 97Didn't find it! 98
from math import sqrtfor n in range(99,89,-1): root = sqrt(n) if root == int(root): print n break else: print "Didn't find it!",n
Didn't find it! 99Didn't find it! 98Didn't find it! 97Didn't find it! 96Didn't find it! 95Didn't find it! 94Didn't find it! 93Didn't find it! 92Didn't find it! 91Didn't find it! 90
range函數,就是不包括後面的邊界~
列表推導式——輕量級迴圈
>>> [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)]
result = []for x in range(3): for y in range(3): result.append((x,y))print result
>>> 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']
比較(Python根據縮排來判斷語句關係)
result = []for x in range(3): for y in range(3): result.append((x,y))print result
[(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)) print result
[(0, 0)][(0, 0), (0, 1)][(0, 0), (0, 1), (0, 2)][(0, 0), (0, 1), (0, 2), (1, 0)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
第六章 抽象
fibs = [0,1]num = input('How many Fibonacci numbers do you want?')for i in range(num-2): fibs.append(fibs[-2] + fibs[-1])print fibs
How many Fibonacci numbers do you want?10[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
函數
def hello(name): return 'Hello,'+name+'!'
>>> print hello('world')Hello,world!>>> print hello('Gumby')Hello,Gumby!
def fibs(num): result = [0,1] for i in range(num-2): result.append(result[-2]+result[-1]) return result
>>> fibs(10)[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]>>> fibs(10)[2]1
記錄函數
def square(x): 'Calculates the square of the number x.' return x*x
def square(x): 'Calculates the square of the number x.' return x*x
並非真正函數的函數
def test(): print 'This is printed' return print 'This is not'
>>> x = test()This is printed>>> x>>> print xNone>>>
參數魔法
>>> def change(n):n = 'Alex'>>> name = 'mr'>>> change(name)>>> name'mr'
>>> def change(n):n[0] = 'Mr. Gumby'>>> names = ['Mrs. Entity','Mrs. Thing']>>> change(names)>>> names['Mr. Gumby', 'Mrs. Thing']>>> >>> names = ['Mrs. Entity','Mrs. Thing']>>> n = names>>> n[0] = 'Mr. Gumby'>>> names['Mr. Gumby', 'Mrs. Thing']>>>
>>> names = ['Mrs. Entity','Mrs. Thing']>>> n = names>>> n is namesTrue>>> n == namesTrue>>> n = names[:]>>> n is namesFalse>>> n == namesTrue
指向同一對象的時候,is就是True,否則就是False