最近好多同窗諮詢有關Python的相關知識,爲此,小編轉載加略微改變成了下面這篇文章,但願給你們帶來幫助,相關Python入門知識,直接訪問:http://edu.51cto.com/course/courseList/id-78.html
html
Python是一門動態語言python
與Java,C等相對,Python不用編譯,像腳本同樣直接運行.這就致使了,全部錯誤都是運行時的!即便有語法錯誤,或者異常,若是程序邏輯沒有執行到,就不會有錯誤.好比一個if分支中有語法錯誤,使用了未定義的函數,但若是未執行到此分支,就能夠正常運行.
動態的另一層意思就是它的類型是動態的,也就是說無需指定變量的類型,在運行時,根據它的內容來決定的類型.
linux
一般來說有二種方式,一種方式是交互式的,就像Shell命令行提示符那樣,交互式的,輸入,就有輸出;
在終端輸入python命令,就進入了Python的命令提示符中:>>>輸入Python語句,解釋器就會執行,並輸出結果,如:
git
[python] view plain copy print?正則表達式
[alex@alexon :~]$python shell
Python 2.7.3 (default, Apr 10 2013, 06:20:15) express
[GCC 4.6.3] on linux2 編程
Type "help", "copyright", "credits" or "license" for more information. 數組
>>> print 'hello, world' app
hello, world
>>>
輸入exit()能夠退出命令提示符.
另一種方式就是腳本,就像Shell的腳本的同樣,把一組命令集合到一塊兒執行,這就能發揮更大的做用.
[python] view plain copy print?
#!/usr/bin/python
print 'hello, world'
不像Java,C/C++以花括號{}來區分語句塊.Python是以縮進來表示語句塊,同一縮進級別爲同一級別的語句塊.
一個腳本文件中的0級縮進是文件加載的時候就會被執行的語句,如上面的print.開啓一個新的縮進須要使用:(冒號),表明下一級別的語句塊,如條件,循環或者函數定義.
縮進最好使用四個空格.並且要注意縮進要一致,使用空格就全都用空格,使用Tab就都使用Tab,混用就可能獲得縮進錯誤:
IndentationError: unindent does not match any outer indentation level
與Java和C中十分相似, +(加), -(減), *(乘), /(除), %(求餘), **(指數運算), = (賦值).以及減便運算,如 +=, -=, *=和/= 等.
賦值運算與其餘語言一致.
邏輯操做
> < <= >= != ==與其餘語言同樣.
不同的有not邏輯非,and邏輯與和or邏輯或.
一行當中,從#開始地方就是註釋.不會影響下一行.
""引號放在文件的開頭,函數的開頭或者一個類的開頭,就是文檔註釋,與Java中的/** ... */做用和目的是同樣的.
若是一行太長了,寫不下了,就須要在下一行接着寫,這時可使用\來告訴Python,下一行繼續.
Python是一個語句放在一行,行尾能夠選擇性的加上;但若是想在一行放多個語句,就須要用;來分隔語句:
a = 1; b = 2; c = 3;
雖然這在語法上可行,但不是一個好習慣,絕大多數的編程規範都是要一行寫一個語句.
int
long
bool
float
與Java中很是接近.能夠近似認爲一致.bool的值是True和False,或者0(False),非0就是True.
這就是Java或C中的數組.它是一個容器,能用來順序的,以整數索引方式檢索, 存儲一組對象.List用[]來表示,如[1, 2, 3]就是一個List;而Tuple用()來表示,如(3, 4, 5)就是一個Tuple.它們的區別在於List是可變的;而Tuple是不可變的.也就是說不能夠增,刪和改.
索引方式除了與Java同樣的以一個整數下標方式外,還能夠指定開始,結束和步長,和使用負索引來分割List:
通用語法格式是:list[start:end:step]
list[index] --- 返回第(index+1)個元素,受C語言影響,下標亦是從0開始
list[start:end] --- 返回從start開始,到end-1,也就是list[start], list[start+1].....list[end-1]
list[start:end:step] --- 與上面相似,只不過每隔step取一個
list[:end] ---- 缺省的開端是0
list[start:] ---- 缺省的結尾是len(list),或者-1
負數索引更是方便,它與正數的對應關係爲:
正數索引 0 1 2 3
數組元素 [1] [3] [5] [7]
負數索引 -4 -3 -2 -1
實例:
[python] view plain copy print?
>>> a = [1, 3, 5, 7];
>>> a[0]
1
>>> a[3]
7
>>> a[-1]
7
>>> a[-2]
5
>>> a[0:3]
[1, 3, 5]
>>> a[1:3:2]
[3]
>>> a[0:3:2]
[1, 5]
>>> a[0:-1:2]
[1, 5]
>>>
List是一個對象,它有一此內置的方法,如:
包含關係: in, not in
[python] view plain copy print?
>>> 3 in a
True
>>> 8 in a
False
>>> 8 not in a
True
>>>
鏈接符: +
[python] view plain copy print?
>>> a + [9, 11]
[1, 3, 5, 7, 9, 11]
重複: *
[python] view plain copy print?
>>> a * 2
[1, 3, 5, 7, 1, 3, 5, 7]
>>>
字符串就是一個字符的數組,List的操做均可以對String直接使用.
[python] view plain copy print?
>>> str = 'hello, world'
>>> str[0:3]
'hel'
>>> str[0:3:2]
'hl'
>>> str[-1]
'd'
>>> str * 2
'hello, worldhello, world'
>>> '3' in str
False
>>> 'le' in str
False
>>> 'el' in str
True
>>> 'ell' not in str
False
>>>
這是一個相似C語言printf和Java中的String.format()的操做符,它能格式化字串,整數,浮點等類型:語句是:
formats % (var1, var2,....)
它返回的是一個String.
[python] view plain copy print?
>>> "Int %d, Float %d, String '%s'" % (5, 2.3, 'hello')
"Int 5, Float 2, String 'hello'"
>>>
至關於Java中的HashMap,用於以Key/Value方式存儲的容器.建立方式爲 {key1: value1, key2: value2, ....}, 更改方式爲dict[key] = new_value;索引方式爲dict[key]. dict.keys()方法以List形式返回容器中全部的Key;dict.values()以List方式返回容器中的全部的Value:
[python] view plain copy print?
>>> box = {'fruits': ['apple','orange'], 'money': 1993, 'name': 'obama'}
>>> box['fruits']
['apple', 'orange']
>>> box['money']
1993
>>> box['money'] = 29393
>>> box['money']
29393
>>> box['nation'] = 'USA'
>>> box
{'money': 29393, 'nation': 'USA', 'name': 'obama', 'fruits': ['apple', 'orange']}
>>> box.keys()
['money', 'nation', 'name', 'fruits']
>>> box.values()
[29393, 'USA', 'obama', ['apple', 'orange']]
>>>
格式爲:
[python] view plain copy print?
if expression:
blocks;
elif expression2:
blocks;
else:
blocks;
其中邏輯表達式能夠加上括號(),也能夠不加.但若是表達式裏面比較混亂,仍是要加上括號,以提升清晰.但總體的邏輯表達式是能夠不加的:
[python] view plain copy print?
>>> a = 3; b = 4; c = 5;
>>> if a == b and a != c:
... print "Are you sure"
... elif (a == c and b == c):
... print "All equal"
... else:
... print "I am not sure"
...
I am not sure
>>>
與Java中相似:
while expression:
blocks
[python] view plain copy print?
>>> i = 0;
>>> while i < 3:
... print "I am repeating";
... i += 1;
...
I am repeating
I am repeating
I am repeating
>>>
與Java中的foreach語法同樣, 遍歷List:
for var in list:
blocks;
[python] view plain copy print?
>>> msg = "Hello";
>>> for c in msg:
... print c;
...
H
e
l
l
o
>>>
這是Python最強大,也是最性感的功能:
list = [expression for var in list condition]
它至關於這樣的邏輯:
list = [];
for var in list:
if condition:
execute expression;
add result of expression to list
return list;
一句話,至關於這麼多邏輯,可見數組推導是一個十分強大的功能:
[python] view plain copy print?
>>> a = range(4);
>>> a
[0, 1, 2, 3]
>>> [x*x for x in a if x % 2 == 0]
[0, 4]
>>>
遍歷列表a,對其是偶數的項,乘方.
如何定義函數
def function_name(args):
function_body;
調用函數的方式function_name(formal_args):
[python] view plain copy print?
>>> def power(x):
... return x*x;
...
>>> power(4)
16
>>>
Python中函數也是一個對象,能夠賦值,能夠拷貝,能夠像普通變量那樣使用.其實能夠理解爲C語言中的指針:
[python] view plain copy print?
<pre name="code" class="python">>>> d = power;
>>> d(2)
4</pre>
<pre></pre>
另外就是匿名函數,或者叫作lambda函數,它沒有名字,只有參數和表達式:
lambda args: expression
[python] view plain copy print?
>>> d = lambda x: x*x;
>>> d(2)
4
lambda最大的用處是用做實參:
[python] view plain copy print?
>>> def iter(func, list):
... ret = [];
... for var in list:
... ret.append(func(var));
... return ret;
...
>>> iter(lambda x: x*x, a)
[0, 1, 4, 9]
>>>
所謂內置函數,就是不用任何導入,語言自己就支持的函數:
print --- 打印輸出
print var1, var2, var3
[python] view plain copy print?
>>> a
[0, 1, 2, 3]
>>> d
<function <lambda> at 0x7f668c015140>
>>> print a, d
[0, 1, 2, 3] <function <lambda> at 0x7f668c015140>
>>>
print與%結合更爲強大:
print formats % (var1, var2, ...):
[python] view plain copy print?
>>> print "today is %d, welcome %s" % (2013, 'alex');
today is 2013, welcome alex
>>>
其實這沒什麼神祕的,前面提到過%格式化返回是一個字串,因此print僅是輸出字串而已,格式化工做是由%來作的.
len()---返回列表,字串的長度
range([start], stop, [step]) --- 生成一個整數列表,從,start開始,到stop結束,以step爲步長
[python] view plain copy print?
>>> range(4)
[0, 1, 2, 3]
>>> range(1,4)
[1, 2, 3]
>>> range(1,4,2)
[1, 3]
>>>
help(func)---獲取某個函數的幫助文檔.
import subprocess;
check_call(commands, shell=True)能夠執行一個命令,並檢查結果:
[python] view plain copy print?
>>> check_call("ls -l .", shell=True);
total 380
-rw-r--r-- 1 alex alex 303137 Jun 28 23:25 00005.vcf
drwxrwxr-x 3 alex alex 4096 Jun 28 23:57 3730996syntheticseismogram
-rw-rw-r-- 1 alex alex 1127 Jun 28 23:45 contacts.txt
-rw-rw-r-- 1 alex alex 3349 Jun 29 00:19 contacts_vcard.vcf
drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Desktop
drwxr-xr-x 3 alex alex 4096 Jun 22 08:59 Documents
drwxr-xr-x 9 alex alex 4096 Jul 3 20:34 Downloads
-rw-r--r-- 1 alex alex 8445 Jun 15 18:17 examples.desktop
drwxrwxr-x 5 alex alex 4096 Jun 19 23:01 gitting
-rw-rw-r-- 1 alex alex 0 Jun 19 20:21 libpeerconnection.log
drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Music
-rw-rw-r-- 1 alex alex 148 Jul 4 22:46 persons.txt
drwxr-xr-x 3 alex alex 4096 Jul 4 23:08 Pictures
drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Public
-rw-rw-r-- 1 alex alex 65 Jul 8 22:15 py.py
-rw-rw-r-- 1 alex alex 271 Jul 4 21:28 speech.txt
-rw-rw-r-- 1 alex alex 93 Jul 3 23:02 speech.txt.bak
drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Templates
drwxrwxr-x 2 alex alex 4096 Jun 22 19:01 Ubuntu One
drwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Videos
0
>>>
check_call是至關於在Shell上執行一個語句,因此能夠發揮想像力,組合Shell命令:
[python] view plain copy print?
>>> check_call("ls -l . | grep 'py'", shell=True);
-rw-rw-r-- 1 alex alex 65 Jul 8 22:15 py.py
0
>>>
check_output(cmds, shell=True)執行命令,並以字串形式返回結果:
[python] view plain copy print?
>>> a = check_output("ls -l .", shell=True);
>>> a
'total 380\n-rw-r--r-- 1 alex alex 303137 Jun 28 23:25 00005.vcf\ndrwxrwxr-x 3 alex alex 4096 Jun 28 23:57 3730996syntheticseismogram\n-rw-rw-r-- 1 alex alex 1127 Jun 28 23:45 contacts.txt\n-rw-rw-r-- 1 alex alex 3349 Jun 29 00:19 contacts_vcard.vcf\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Desktop\ndrwxr-xr-x 3 alex alex 4096 Jun 22 08:59 Documents\ndrwxr-xr-x 9 alex alex 4096 Jul 3 20:34 Downloads\n-rw-r--r-- 1 alex alex 8445 Jun 15 18:17 examples.desktop\ndrwxrwxr-x 5 alex alex 4096 Jun 19 23:01 gitting\n-rw-rw-r-- 1 alex alex 0 Jun 19 20:21 libpeerconnection.log\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Music\n-rw-rw-r-- 1 alex alex 148 Jul 4 22:46 persons.txt\ndrwxr-xr-x 3 alex alex 4096 Jul 4 23:08 Pictures\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Public\n-rw-rw-r-- 1 alex alex 65 Jul 8 22:15 py.py\n-rw-rw-r-- 1 alex alex 271 Jul 4 21:28 speech.txt\n-rw-rw-r-- 1 alex alex 93 Jul 3 23:02 speech.txt.bak\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Templates\ndrwxrwxr-x 2 alex alex 4096 Jun 22 19:01 Ubuntu One\ndrwxr-xr-x 2 alex alex 4096 Jun 15 18:43 Videos\n'
>>> b = check_output("ls -l . | grep 'py'", shell=True);
>>> b
'-rw-rw-r-- 1 alex alex 65 Jul 8 22:15 py.py\n'
>>>
不用我說你就知道它的強大之處了!惟一須要注意的就是換行符也在裏面,處理的時候須要注意!
Python也是支持正則表達式的,至於正則表達式,跟其餘的語言如Java,C沒什麼差異,這裏說說如何使用正則表達式來進行匹配:
[python] view plain copy print?
import re;
p = re.compile(expression);
m = p.search(target);
if m != None:
# got match
else:
# no match
如:
[python] view plain copy print?
>>> message = 'Welcome to the year of 2013';
>>> import re;
>>> p = re.compile('(\d+)');
>>> m = p.search(message);
>>> m
<_sre.SRE_Match object at 0x7f668c015300>
>>> print m.group(1)
2013
>>>
這些就是Python的入門基礎知識看,瞭解更多:http://edu.51cto.com/course/courseList/id-78.html