我們會首先介紹print和import的更多使用方法,然后是介紹條件語句和循環語句。隨后會介紹列表推導式,最后介紹pass、exec、eval的用法。
print和import的介紹
使用逗號輸出
輸出多個表達式的值是可行的,如下:
>>> print 'Age:', 42
Age: 42
print的內容并沒有構成一個元組,除非加上括號:
>>> 1,2,3
(1, 2, 3)
>>> print 1,2,3
1 2 3
>>> print (1,2,3)
(1, 2, 3)
不希望格式化字符串,可以通過這種辦法來輸出:
>>> greeting = 'Hello,'
>>> salutation = 'Mr.'
>>> name = 'Gumby'
>>> print greeting, salutation, name
Hello, Mr. Gumby
如果想通過增加一個','
直接在print中多輸出一個,
是不行的,因為,
前后被加上了空格,通過+','
增加逗號是一種可行的辦法:
>>> greeting = 'Hello'
>>> salutation = 'Mr.'
>>> greeting = 'Hello'
>>> print greeting, ',', salutation, name
Hello , Mr. Gumby
>>> print greeting + ',', salutation, name
Hello, Mr. Gumby
如果在結尾加上,
,下一行語句的輸出會和前一行語句在同一行輸出:
print 'Hello,',
print 'World!'
#注:這只在腳本中起作用,在交互式命令行中所有語句都會被單獨執行。
$ python hello.py
Hello, World!
導入
導入有如下幾種形式, 后面幾種方法可以防止引用的方法重名:
import module
import module as rmodule
from module import *
from module import method
from module import method as rmethod
賦值
序列解包
多個賦值操作可以同時進行:
>>> x,y,z =1,2,3
>>> print x,y,z
1 2 3
或者直接用來交換兩個變量:
>>> x,y = y,x
>>> print x,y,z
2 1 3
如上所做的操作叫做序列解包,就是將一個序列的值分別由變量組成的序列中。當函數或方法返回元組時該特性尤其有用:
>>> couple = {'name': 'andrew', 'title': 'software engineer'}
>>> key, value = couple.popitem()
>>> key
'name'
>>> value
'andrew'
鏈式賦值
通過如下方式可以將一個值賦給多個變量的快捷方式:
x = y = z
增量賦值
形如 x += 2
, x *= 3
都是增量賦值,增量賦值對*
、/
、%
都適用。
語句塊
在介紹后面的知識之前需要簡單介紹一下語句塊。 語句塊即符合條件時候執行,或者多次被執行的代碼片段。在其他編程語言會使用{}包裹的方式,在Python則是通過縮進來標識語句塊,冒號被視作語句塊的開始。
條件和條件語句
這就是布爾變量的作用
除了 False
、None
、“”
、{}
、[]
、()
外的所有值都等價于True。
條件執行和if語句
條件判定為真,后面的語句塊就會被執行,如下:
name = raw_input("What's your name ?")
if name == 'Gumby':
print 'Hello,' + name
$ python hello.py
What's your name ?Gumby
Hello,Gumby
else子句
name = raw_input("What's your name ?")
if name == 'Gumby':
print 'Hello,' + name
else:
print 'Hello, stranger'
$ python hello.py
What's your name ?Jackson
Hello, stranger
elseif子句
如果有多個條件,可以適用elif(else if的簡寫):
num = raw_input('Enter a number:')
if num > 0:
print 'Number is positive'
elif num < 0:
print 'Number is negative'
else:
print 'Number is zero'
嵌套代碼塊
if語句里面能夠嵌套if語句,保持正確的縮進即可。
更復雜的條件
- 比較運算符:
>、<、=、is、not、in
- 相等運算符:
==
- 同一性運算符:
is
,判定是否指向同一個對象 - 成員資格運算符:
in
- 字符串序列比較
- 布爾運算符:
and、or、not
斷言
當程序結果不符合預期的時候,可以結束程序,使用的就是斷言,如下是一個使用斷言的例子:
>>> age = -1
>>> assert age < 100 and age > 0, 'age should between 0 and 100'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: age should between 0 and 100
循環
while循環
name = ''
while not name:
name = raw_input('Enter your name:')
print 'Hello,' + name
如上例,如果不輸入名字直接按回車,會一直要求輸入。
for循環管
for num in range(1,10):
print num
這里使用了一個range函數,參數類似于切片包含下限,不包含上限。
循環遍歷字典元素
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print key , 'correspond to :', d[key]
一些迭代工具
迭代序列時一些函數非常有用,有的屬于Python的內奸函數,有的則位于itertools模塊中。
- 并行迭代
要同時展示兩部分的信息,可以通過如下方法:
names = ['james', 'lebron', 'jordan']
numbers = [6, 24, 23]
for i in range(len(names)):
print names[i], "'s number is ", numbers[i]
內件函數zip提供了并行迭代的功能:
names = ['james', 'lebron', 'jordan']
numbers = [6, 24, 23]
for name, numer in zip(names, numbers):
print name, "'s number is ", number
- 索引迭代
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[consored]'
enumerte可以提供 索引-值 對,方便循環便利列表的時候同時獲取到索引。
- 翻轉和排序迭代
reversed和sorted對應于reverse和sort,區別在于它們并不改變對象結構,而是返回翻轉或者排序后的版本:
>>> sorted([12,4,3])
[3, 4, 12]
>>> sorted('Hello')
['H', 'e', 'l', 'l', 'o']
>>> reversed('Hello')
<reversed object at 0x1006e7e10>
>>> list(reversed('Hello'))
['o', 'l', 'l', 'e', 'H']
>>> ''.join(list(reversed('hello')))
'olleh'
跳出循環
break用于跳出循環。continue用于跳過當前輪循環進入到下一輪循環的判定條件。簡單不哆嗦。
循環中的else子句
有這么一個場景: 在循環中出現某種情況導致我們跳出循環,在循環以外我們要知道是否有過跳出, 沒有跳出過的話執行某段代碼。 該場景可以通過在循環內,當滿足條件的時候標記布爾值來實現。
在Python中有一種更簡便的代碼:else子句。該形式對于while、for都適用:
from math import sqrt
for number in range(99, 81, -1):
root = sqrt(number)
if root == int(number):
print n
break
else:
print "Didn't find it!"
程序將輸出 'Didn't find it!',如果跟個人預期不一致請注意復習邊界值。
列表推導式
列表推導式是用列表創建新列表的方式:
>>> [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)]
pass、del以及exec
什么都沒發生
因為空代碼塊是非法的,所以pass便被用來占位置。
使用del刪除
>>> scoundrel = {'name':'james', 'age':30}
>>> james = scoundrel
>>> scoundrel = None
>>> james
{'age': 30, 'name': 'james'}
如上,scoundrel被設置為None以后,james還是可以訪問到字典。除非james也被設置為None,字典才會被垃圾回收掉。
>>> scoundrel = {'name':'james', 'age':30}
>>> del scoundrel
>>> scoundrel
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'scoundrel' is not defined
如上,使用del刪除對象,不僅能夠刪除對象的引用,連名字也會被刪除掉。
>>> x = ['hello', 'world']
>>> y = x
>>> y
['hello', 'world']
>>> y[1] = 'python'
>>> x
['hello', 'python']
>>> del x
>>> y
['hello', 'python']
如上,前半部分都好理解。后半部分可能要 注意:不同于Java和JavaScript,Python中的刪除是刪除的對象引用和名稱,對象本身還是存在的!
使用exec和eval執行和求值字符串
- exec()
>>> exec 'print "Hello, World!"'
Hello, World!
- eval()
eval會計算python表達式,并返回結果值:
>>> eval(raw_input('Please enter an expression:'))
Please enter an expression:12 + 2*4
20
>>> exec(raw_input('Please enter number:'))
Please enter number:1+2