用於交互使用:
>>> user = raw_input('Enter login name:')
Enter login name:root
>>> print user
root
交互使用,將輸出的數字型轉化爲整形,並通過% 進行替換
註解:%s 表示由一個字符串替換,%d表示由一個整數來替換%f由一個浮點數來替換
>>> num = raw_input('Now enter a number:')
Now enter a number:1024
>>> print 'Doubling your number: %d' % (int(num) * 2)
Doubling your number: 2048
>>>
可以通過調用內建函數help查看對應生詞函數的使用幫助
help(raw_input)
井號後都是註釋部分
######ffffffffffffffff
運算符
+ - * / // % **
//:(用於浮點除法,對結果進行四捨五入)
變量和賦值操作。
>>> counter=0 ####整數
>>> miles = 1000.0 #####浮點數
>>> name = 'Bob' #####字符串
>>> counter = counter +1 ####對1個整數加1
>>> kilometers = 1.609 * miles ####浮點數乘法賦值
>>> print "%f miles is the same as %s km" % (miles,kilometers)
1000.000000 miles is the same as 1609.0 km
>>>
數字類型:
int(有符號整數)
long(長整數)
bool(布爾值)
float(浮點值)
complex(負數)
[:] 可以截取到字符串內容
>>>pystr = 'Python'
>>> pystr
'Python'
>>> pystr[2:5]
'tho'
>>>
[:2] 字符串從0開始截取到第二個字符串(不包含第二個字符串,s)
>>> iscool = 'is cool!'
>>> iscool[:2]
'is'
>>>
[3:] 字符串從3開始截取到最後(不包含第:三個字符串,s)
>>> iscool[3:]
'cool!'
>>>
[-1] 截取最後一個字符串
>>> iscool[-1]
'!'
>>>
可以加空格
>>> pystr + ' ' +iscool
'Python is cool!'
>>>
字符串*2
>>> pystr * 2
'PythonPython'
>>>
將特殊字符*20
>>> '-' * 20
'--------------------'
>>>
添加回車符
>>> pystr = '''python
... is cool'''
>>> pystr
'python\nis cool'
>>> print pystr
python
is cool
>>>
列表與切片
>>> aList = [1,2,3,4]
>>> aList
[1, 2, 3, 4]
>>> aList[0]
1
>>> aList[2:]
[3, 4]
>>> aList[1] = 5 ####將分片1替換成 5
[1, 5, 3, 4]
>>> aTuple = ('robots', 77, 93, 'try')
>>> aTuple
('robots', 77, 93, 'try')
>>> aTuple[:3]
('robots', 77, 93)
>>>
字典,由鍵值對構成,字典元素用大括號包裹
>>> aDict = {'host':'earth'}
>>> aDict['port'] = 80
>>> aDict
{'host': 'earth', 'port': 80}
>>>
>>> aDict.keys() #####將字典的鍵值對取出
['host', 'port']
>>>
>>> aDict['host'] ###可以取出字典對應的鍵值對。
'earth'
>>> aDict
{'host': 'earth', 'port': 80} ###可以取出字典對應的鍵值對。
>>> aDict['port']
80
>>>
while小程序
>>> counter = 0
>>> while counter < 3:
... print 'loop #%d' % (counter)
... counter += 1
...
loop #0
loop #1
loop #2
for小程序,Python中的for接受可迭代對象作爲其參數,每次迭代其中一個
(如下代碼所示:print默認給每一行添加了換行符)
>>> print 'I like to use the Internet for:'
I like to use the Internet for:
>>> for item in ['e-mail', 'net-surfing', 'homework', 'chat']:
... print item
...
net-surfing
homework
chat
>>>
小例子
>>> for eachNum in range(3):
... print eachNum
...
0
1
2
>>>
range()函數和len()函數一起使用,顯示每一個元素及其索引值
>>> for i in range(len(foo)):
... print foo[i], '(%d)' % i
...
a (0)
b (1)
c (2)
>>>
循環一般有個約束,要麼循環索引,要麼循環元素,enumerate同時做到了這2點
>>> for i, ch in enumerate(foo):
... print ch, '(%d)' % i
...
a (0)
b (1)
c (2)
>>>
列表解析:用for循環將所有值放到列表中,例如range(4)會得到0,1,2,3循環時
>>> squared = [x ** 2 for x in range(4)]
>>> for i in squared:
... print i
...
0
1
4
9
列表解析,較複雜的操作,將符合的值挑選出放進列表:例如 if not x % 2將餘數不能整除2的剔除,剩餘的數在 x ** 2
>>> sqdEvens = [x ** 2 for x in range(8) if not x % 2 ]
>>> for i in sqdEvens:
... print i
...
0
4
16
36
>>>
#!/usr/bin/env python
filename = raw_input('Enter file name: ')
fobj = open(filename, 'r') 選擇需要打開的文件名,r表示讀取,w表示寫入,a表示添加
for i in fobj:
print i, 這裏加,逗號的作用是爲了抑制文本里的換行符,因爲文本里已自帶換行符
fobj.close()
給代碼添加錯誤檢測機異常處理功能,將他們封裝在try-except中
#!/usr/bin/env python
try:
filename = raw_input('Enter file name:')
fobj = open(filename, 'r')
for i in fobj:
print i,
fobj.close()
except IOError, e:
print "eeeee", e
執行腳本後的錯誤異常,說明沒有找到a.t文本
[root@iZ28c21psoeZ zby]# ./open_bak.py
Enter file name:a.t
eeeee [Errno 2] No such file or directory: 'a.t'
python 中的函數使用小括號()調用的,函數在調用前必須先定義,如果函數中沒有return語句,就會自動返回None對象。
如下是如何定義的小例子
>>> def function_name(arguments):
... "optional documentation string"
... function_suite
...
>>>
接下來如何做,請耐心觀看,如何調用函數,
這個函數,做的是在我的值上加上我的活,他接受一個對象,並將它的值加到自身,然後返回和。
python調用函數與其他高級語言一樣,函數名加上函數運算符,一對小括號。
>>> def addMe2Me(x):
... 'apply + operation to argument'
... return (x + x)
...
>>> addMe2Me(4.25)
8.5
>>> addMe2Me(10)
20
>>> addMe2Me(102)
204
>>> addMe2Me(python)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> addMe2Me('python')
'pythonpython'
>>>
模塊可以包含可執行代碼,函數和類或者這些東西的組合,
一個模塊創建後,可以從另一個模塊中使用import語句導入這個模塊來使用。
接着向下看,如何導入模塊
>>> import sys
>>> sys.stdout.write('Hello, World!\n')
Hello, World!
>>> sys.platform
'linux2'
>>> sys.version
'2.6.6 (r266:84292, Jan 22 2014, 09:42:36) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)]'
練習題:
使用while語句和for語句,輸出一個0到10 的數,確保是0到10 而不是0到9 或者1到10
>>> i = 0
>>> while i < 11:
... print i 這邊一定要先打印,在逐步加1
... i += 1
...
0
1
2
3
4
5
6
7
8
9
10
>>>
for循環
>>> for n in range(11):
... print n
...
0
1
2
3
4
5
6
7
8
9
10
條件判斷,判斷1個數是整數還是負數,或者等於0 ,開始先用固定的數值,然後修改代碼支持,用戶輸入數值進行判斷。
>>> n = int(raw_input('nihao'))
nihao123
>>> if n < 0:
... print 'negative'
... elif n > 0:
... print 'positive'
... else:
... print 'zero'
...
positive
>>>