1.python基礎入門
提示:css
- 語法基於python3.x版本(會提示2.x版本和3.x版本的區別)
- Python命令行將以>>>開始,好比 >>>print ('Hello World!')
-
window上會使用JetBrains PyCharm 5.0.2專業版html
-
Python官網:http://www.python.org/java
Python文檔下載地址:www.python.org/doc/python
一.python簡介linux
Python是一種簡單易學,功能強大的編程語言,它有高效率的高層數據結構,簡單而有效地實現面向對象編程。Python簡潔的語法和對動態輸入的支持,再加上解釋性語言的本質,使得它在大多數平臺上的許多領域都是一個理想的腳本語言,特別適用於快速的應用程序開發。 Python能夠應用於衆多領域,如:數據分析、組件集成、網絡服務、圖像處理、數值計算和科學計算等衆多領域。算法
Python 是一個高層次的結合瞭解釋性、編譯性、互動性和麪向對象的腳本語言。 shell
Python 的設計具備很強的可讀性,相比其餘語言常用英文關鍵字,其餘語言的一些標點符號,它具備比其餘語言更有特點語法結構。(引用於菜鳥教程)數據庫
2、Python 發展歷史 編程
Python 是由 Guido van Rossum 在八十年代末和九十年代初,在荷蘭國家數學和計算機科學研究所設計出來的。vim
Python 自己也是由諸多其餘語言發展而來的,這包括 ABC、Modula-三、C、C++、Algol-6八、SmallTalk、Unix shell 和其餘的腳本語言等等。
像 Perl 語言同樣,Python 源代碼一樣遵循 GPL(GNU General Public License)協議。
如今 Python 是由一個核心開發團隊在維護,Guido van Rossum 仍然佔據着相當重要的做用,指導其進展。(引用於菜鳥教程)
3、Python 特色
-
1.易於學習:Python有相對較少的關鍵字,結構簡單,和一個明肯定義的語法,學習起來更加簡單。
-
2.易於閱讀:Python代碼定義的更清晰。
-
3.易於維護:Python的成功在於它的源代碼是至關容易維護的。
-
4.一個普遍的標準庫:Python的最大的優點之一是豐富的庫,跨平臺的,在UNIX,Windows和Macintosh兼容很好。
-
5.互動模式:互動模式的支持,您能夠從終端輸入執行代碼並得到結果的語言,互動的測試和調試代碼片段。
-
6.可移植:基於其開放源代碼的特性,Python已經被移植(也就是使其工做)到許多平臺。
-
7.可擴展:若是你須要一段運行很快的關鍵代碼,或者是想要編寫一些不肯開放的算法,你可使用C或C++完成那部分程序,而後從你的Python程序中調用。
-
8.數據庫:Python提供全部主要的商業數據庫的接口。
-
9.GUI編程:Python支持GUI能夠建立和移植到許多系統調用。
-
10.可嵌入: 你能夠將Python嵌入到C/C++程序,讓你的程序的用戶得到"腳本化"的能力。(引用於菜鳥教程)
4、python版本區別
1.print使用方法
2.7版本 print "yaoyao" or print ("yaoyao") 3.x版本 print ("yaoyao")
2.Py3.X源碼文件默認使用utf-8編碼
3.模塊命名修改
注:(twisted模塊還未徹底支持python3)
version | 2.x | 3.x |
print " "或者print()打印均可以正常輸出 | 只能print()這種形式打印,不然會出現 SyntaxError |
|
input raw_inut |
input:輸出原生的數據類型,輸入什麼類型的值,就輸出什麼類型 raw_input:所有以字符串形式輸出 |
3.x取消了raw_input方法,只能使用input() 方式提示輸入字符串, 該方法和2.x版本的raw_input() 若是想要實現與2.x input()輸出原生數據類型的值, 可使用eval(input()) |
class | 2.x支持新式類,和經典類,使用新式類時,類繼承順序會影響最終繼承的結果 | 必須使用新式類,解決了類間繼承順序問題 |
eg. | 例如:1/2,2.x輸出的值爲0 | 例如:1/2 3.x輸出的值爲0.5 |
4. 語法
5、Python解釋器
1.Cpython
Python的官方版本,使用C語言實現,使用最爲普遍,CPython實現會將源文件(py文件)轉換成字節碼文件(pyc文件),而後運行在Python虛擬機上
1
|
程序----(c解釋器)----(字節碼)----(機器碼)-----cpu
|
2.Jyhton
Python的Java實現,Jython會將Python代碼動態編譯成Java字節碼,而後在JVM上運行。
1
|
程序
-
-
-
-
(java解釋器)
-
-
-
-
(字節碼)
-
-
-
-
(機器碼)
-
-
-
-
-
cpu
|
3.IronPython
Python的C#實現,IronPython將Python代碼編譯成C#字節碼,而後在CLR上運行。(與Jython相似)
1
|
程序
-
-
-
-
(c
#解釋器)----(字節碼)----(機器碼)-----cpu
|
4.PyPy(特殊)
Python實現的Python,將Python的字節碼字節碼再編譯成機器碼。
1
|
程序
-
-
-
-
(c
#解釋器)----(字節碼)----(機器碼)-----cpu
|
-
六.pyc文件
-
執行Python代碼時,若是導入了其餘的 .py 文件,那麼,執行過程當中會自動生成一個與其同名的 .pyc 文件,該文件就是Python解釋器編譯以後產生的字節碼。
-
ps:代碼通過編譯能夠產生字節碼;字節碼經過反編譯也能夠獲得代碼。
七.python安裝
1.window
(1)進入官網下載安裝包:
https://www.python.org/downloads/
2.linux
注: 2.x升級到3.x版本
(1)安裝3.x包:
1
2
3
|
sudo apt
-
get install python3.
6
python3.6
>>>
|
八. 用戶交互
1:linux
(1)輸出
1
2
3
|
python3.6
>>>
print
(
'Hello World!'
)
Hello World!
|
print是一個經常使用函數,其功能就是輸出括號中得字符串。(在Python 2.x中,print還能夠是一個關鍵字,可寫成print 'Hello World!')
寫入如下內容,保存而且退出。
1
2
3
4
5
6
7
8
9
|
$vim HelloWorld.py
#!/usr/bin/env python #必須聲明是什麼解釋器來解釋此腳本
print
(
'Hello World!'
)
#保存退出
#python HelloWorld.py #運行py
Hello World!
或者給該文件增長可執行權限
chmod a
+
x HelloWorld.py
.
/
HelloWorld.py
Hello World
|
(2)輸入
Python提供了一個input()
,可讓用戶輸入字符串,並存放到一個變量裏。好比輸入用戶的名字:
1
2
3
4
5
6
7
|
>>> name
=
input
(
'您的名字'
)
您的名字
>>> name
=
input
(
'您的名字'
)
您的名字yaoyao
>>> name
'yaoyao'
>>>
|
9、註釋
1.單行註釋
註釋符#
例:
1
|
#代碼代碼代碼被註釋
|
2.多行註釋
'''
'''
例:
1
2
3
4
|
'''第一句
第二句
第三句
'''
|
10、行與縮進
學習Python與其餘語言最大的區別就是,Python的代碼塊不使用大括號({})來控制類,函數以及其餘邏輯判斷。python最具特點的就是用縮進來寫模塊。
縮進的空白數量是可變的,可是全部代碼塊語句必須包含相同的縮進空白數量,這個必須嚴格執行。以下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
if
True
:
print
"True"
else
:
print
"False"
如下代碼將會執行錯誤:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py
if
True
:
print
"Answer"
print
"True"
else
:
print
"Answer"
# 沒有嚴格縮進,在執行時保持
print
"False"
#提示如下錯誤
$ python test.py
File
"test.py"
, line
5
if
True
:
^
IndentationError: unexpected indent
|
11、變量與賦值
1.聲明變量
1
2
3
|
>>> name
=
'yaoyao'
>>> name
'yaoyao'
|
聲明一個變量爲name 值爲:yaoyao
1
2
3
4
|
>>> name
=
"yaoyao"
>>> age
=
20
>>>
print
(name,age)
(
'yaoyao'
,
20
)
|
查看變量內存地址
1
2
|
>>>
id
(age)
43102336
|
2.變量聲明要求
- 變量名只能是 字母、數字或下劃線的任意組合
- 變量名的第一個字符不能是數字
1
2
3
|
>>>
import
keyword
>>> keyword.kwlist
[
'False'
,
'None'
,
'True'
,
'and'
,
'as'
,
'assert'
,
'break'
,
'class'
,
'continue'
,
'def'
,
'del'
,
'elif'
,
'else'
,
'except'
,
'finally'
,
'for'
,
'from'
,
'global'
,
'if'
,
'import'
,
'in'
,
'is'
,
'lambda'
,
'nonlocal'
,
'not'
,
'or'
,
'pass'
,
'raise'
,
'return'
,
'try'
,
'while'
,
'with'
,
'yield'
]
|
1.數字
int (整數型)
在32位機器上,整數的位數爲32位,取值範圍爲-2**31~2**31-1,即-2147483648~2147483647
在64位系統上,整數的位數爲64位,取值範圍爲-2**63~2**63-1,即-9223372036854775808~9223372036854775807
float (浮點型)
浮點數用來處理實數,即帶有小數的數字。相似於C語言中的double類型,佔8個字節(64位),其中52位表示底,11位表示指數,剩下 的一位表示符號。
long(長整型)
跟C語言不一樣,Python的長整數沒有指定位寬,即:Python沒有限制長整數數值的大小,但實際上因爲機器內存有限,咱們使用的長整數數值不可能無限大。注意,自從Python2.2起,若是整數發生溢出,Python會自動將整數數據轉換爲長整數,因此現在在長整數數據後面不加字母L也不會致使嚴重後果了。
2.布爾值
布爾值和布爾代數的表示徹底一致,一個布爾值只有True
、False
兩種值,要麼是True
,要麼是False
,在Python中,能夠直接用True
、False
表示布爾值(請注意大小寫),也能夠經過布爾運算計算出來:
1
2
3
4
|
>>>
True
True
>>>
False
False
|
3.字符串 (即不能修改的字符list)
字符串是一個總體。若是你想直接修改字符串的某一部分,是不可能的。但咱們可以讀出字符串的某一部分。
字符串包含判斷操做符:
1
2
3
|
例:
in
,
not
in
"He"
in
str
"she"
not
in
str
|
字符串經常使用功能:
字符串格式化輸出
1
2
3
4
5
6
7
8
9
10
|
#!/usr/bin/env python
name
=
input
(
"name:"
)
age
=
input
(
"age:"
)
job
=
input
(
"job:"
)
print
(
'''
Infomation of %s
name:%s
age:%s
job:%s
'''
%
(name,name,age,job))
|
十3、列表
Python內置的一種數據類型是列表:list。list是一種有序的集合,能夠隨時添加和刪除其中的元素。
建立列表:
好比列出日本的美女:
1
2
3
|
>>> gril
=
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
,
'sondaofeng'
]
>>> gril
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
,
'sondaofeng'
]
|
用dir()函數能夠查看此列表能使用的方法
1
2
|
>>>
dir
(gril)
[
'__add__'
,
'__class__'
,
'__contains__'
,
'__delattr__'
,
'__delitem__'
,
'__dir__'
,
'__doc__'
,
'__eq__'
,
'__format__'
,
'__ge__'
,
'__getattribute__'
,
'__getitem__'
,
'__gt__'
,
'__hash__'
,
'__iadd__'
,
'__imul__'
,
'__init__'
,
'__iter__'
,
'__le__'
,
'__len__'
,
'__lt__'
,
'__mul__'
,
'__ne__'
,
'__new__'
,
'__reduce__'
,
'__reduce_ex__'
,
'__repr__'
,
'__reversed__'
,
'__rmul__'
,
'__setattr__'
,
'__setitem__'
,
'__sizeof__'
,
'__str__'
,
'__subclasshook__'
,
'append'
,
'clear'
,
'copy'
,
'count'
,
'extend'
,
'index'
,
'insert'
,
'pop'
,
'remove'
,
'reverse'
,
'sort'
]
|
基本操做:
用索引來訪問list中每個位置的元素,索引是從0
開始的
1
2
3
4
5
6
|
>>> gril
=
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
,
'sondaofeng'
]
>>> gril.index(
'cangjingkong'
)
0
>>> gril.index(
'xiaoze'
)
1
>>>
|
切片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
>>> gril
=
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
,
'sondaofeng'
]
# 切割列表並返回新的列表
>>> gril[
1
:
2
]
[
'xiaoze'
]
>>> gril[
0
:
3
]
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
]
>>> gril[:
3
]
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
]
>>> gril[:
-
1
]
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
]
>>> gril[:
1
]
[
'cangjingkong'
]
>>> gril[
-
2
]
'tenglan'
>>>
|
追加
1
2
3
|
>>> gril.append(
'zaochuan'
)
>>> gril
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
,
'sondaofeng'
,
'zaochuan'
]
|
刪除
1
2
3
|
>>> gril.pop() #返回最後一個元素,並從list中刪除
>>> gril
[
'cangjingkong'
,
'xiaoze'
,
'tenglan'
,
'sondaofeng'
]
|
1
2
3
|
>>> gril.remove(
'xiaoze'
) #remove刪除指定值
>>> gril
[
'cangjingkong'
,
'tenglan'
,
'sondaofeng'
,
'zaochuan'
]
|
1
2
3
|
>>> gril.insert(
2
,
'mahuateng'
)
>>> gril
[
'cangjingkong'
,
'tenglan'
,
'mahuateng'
,
'sondaofeng'
,
'zaochuan'
]
|
統計.count
1
2
3
|
>>> gril.insert(
2
,
'mahuateng'
)
>>> gril
[
'cangjingkong'
,
'tenglan'
,
'mahuateng'
,
'sondaofeng'
,
'zaochuan'
]
|
反轉
1
2
3
4
5
|
>>> gril
[
'cangjingkong'
,
'tenglan'
,
'mahuateng'
,
'sondaofeng'
,
'zaochuan'
,
'tenglan'
]
>>> gril.reverse()
>>> gril
[
'tenglan'
,
'zaochuan'
,
'sondaofeng'
,
'mahuateng'
,
'tenglan'
,
'cangjingkong'
]
|
十4、元組
Python的元組與列表相似,不一樣之處在於元組的元素不能修改。
元組使用小括號,列表使用方括號。
元組建立很簡單,只須要在括號中添加元素,並使用逗號隔開便可。
建立元組:
1
2
3
|
>>> boy=(
'mayun'
,
'aobama'
,
'liyanhong'
,
'mahuateng'
)
>>> boy
(
'mayun'
,
'aobama'
,
'liyanhong'
,
'mahuateng'
)
|
支持的方法:
1
2
|
>>> dir(boy)
[
'__add__'
,
'__class__'
,
'__contains__'
,
'__delattr__'
,
'__dir__'
,
'__doc__'
,
'__eq__'
,
'__format__'
,
'__ge__'
,
'__getattribute__'
,
'__getitem__'
,
'__getnewargs__'
,
'__gt__'
,
'__hash__'
,
'__init__'
,
'__iter__'
,
'__le__'
,
'__len__'
,
'__lt__'
,
'__mul__'
,
'__ne__'
,
'__new__'
,
'__reduce__'
,
'__reduce_ex__'
,
'__repr__'
,
'__rmul__'
,
'__setattr__'
,
'__sizeof__'
,
'__str__'
,
'__subclasshook__'
,
'count'
,
'index'
]
|
建立空元組
1
2
3
4
|
>>> boy.index(
'mayun'
)
0
>>> boy.index(
'liyanhong'
)
2
|
基本操做:
1
2
3
4
|
>>> boy.index(
'mayun'
)
0
>>> boy.index(
'liyanhong'
)
2
|
切片
1
2
|
tuple(gril)
list(boy)
|
長度
1
2
|
tuple(gril)
list(boy)
|
list 和 tuple 的相互轉化
1
2
|
tuple(gril)
list(boy)
|
十5、字典
字典是另外一種可變容器模型,且可存儲任意類型對象,如其餘容器模型。
字典由鍵和對應值成對組成。字典也被稱做關聯數組或哈希表。
建立字典:
1
2
3
|
>>> dict = {
'name'
:
'liuyao'
,
'age'
:
'20'
,
'job'
:
'it'
}
>>> dict
{
'job'
:
'it'
,
'age'
:
'20'
,
'name'
:
'liuyao'
}
|
每一個鍵與值用冒號隔開(:),每對用逗號分割,總體放在花括號中({})。
鍵必須獨一無二,但值則沒必要。
值能夠取任何數據類型,但鍵必須是不可變的,如字符串,數字或元組。
注:type()能夠查看變量類型
十6、運算符
1.算術運算符
如下假設變量a爲10,變量b爲20:
2.比較運算符
如下假設變量a爲10,變量b爲20:
3.賦值運算符
如下假設變量a爲10,變量b爲20:
4.位運算
按位運算符是把數字看做二進制來進行計算的。Python中的按位運算法則以下:
5.邏輯運算符
Python語言支持邏輯運算符,如下假設變量a爲10,變量b爲20:
6.成員運算符
7.身份運算符
身份運算符用於比較兩個對象的存儲單元
8.運算符優先級
十7、字符編碼
ASCII(American Standard Code for Information Interchange,美國標準信息交換代碼)是基於拉丁字母的一套電腦編碼系統,主要用於顯示現代英語和其餘西歐語言,其最多隻能用 8 位來表示(一個字節),即:2**8 = 256,因此,ASCII碼最多隻能表示 256 個符號。
Unicode Unicode(統一碼、萬國碼、單一碼)是一種在計算機上使用的字符編碼。 Unicode 是爲了解決傳統的字符編碼方案的侷限而產生的,它爲每種語言中的每 個字符設定了統一而且惟一的二進制編碼,規定雖有的字符和符號最少由 16 位 來表示(2個字節),即:2 **16 = 65536
UTF-8 utF-8,是對Unicode編碼的壓縮和優化,他再也不使用最少使用2個字節,而是將 全部的字符和符號進行分類:ascii碼中的內容用1個字節保存、歐洲的字符用2個 字節保存,東亞的字符用3個字節保存...
python 2.x版本默認string字符編碼,1個字符只能存8bit,可使用內置函數,chr()和ord() 進行字符轉換
python 3.x默認使用unicode編碼格式,可使用內置函數unichr()和ord()進行字符轉換
附:使sublime text 編譯 python 時支持中文:
工具-編譯系統-新編譯系統
{
"cmd": ["C:/Program Files (x86)/Python36-32/python.exe","-u","$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"encoding": "cp936"
}
十8、命名規範
python變量名(標識符)只能以字母或下劃線開頭,且不能包含特殊字符,
注意python保留關鍵字不能看成變量名,這樣等於重寫python的內置方法,可能會影響其餘方法的調用。
python保留字
#經過導入keyword模塊,咱們能夠查看當前python保留了哪些關鍵字 import keyword #查看python保留關鍵字 keyword.kwlist #2.x 輸出 ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] #3.x 輸出 ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] #注意,3.x新增了['False','None','True','nonlocal']同時去除了2.x ['exec']的關鍵字,你們在命名規範時,應該遵循3.x的關鍵字,便於向後兼容 #若是不肯定該變量名是否爲關鍵字,也能夠經過下面這種方法,檢查是爲關鍵字 keyword.iskeyword('name') #返回False,說明該變量名不是系統保留關鍵字,便可用。
爲了書寫規範,建議變量名使用統一的風格書寫,例如:駝峯式 SunOfBeach 或者 sun_of_beach
單個前導下劃線開頭的標識符,意味着約定爲私有的
兩個前導下劃線開頭的標識符,表示強烈專用的標識符
若是標識符還有兩個下劃線結束,則該標識符是語言的特殊名稱
十9、判斷
條件判斷if...else if <條件判斷1>: <執行1> else: <執行4>
例:
if sex == "girl": print('正確') else: print('錯誤') if sex == "gril": print('gril') elif sex == "man": print('man') elif sex == "ren": print('ren') else: print('no')
二10、循環
1.while
while 判斷條件:
執行語句……
1
2
3
4
5
6
7
8
9
10
|
LuckyNum =
6
while
True:
InLuckyNum =
int
(input(
'please your lucky number:'
))
if
InLuckyNum == LuckyNum:
print(
'bingo '
)
break
elif InLuckyNum < LuckyNum:
print(
'please input big'
)
else
:
print(
'please input small'
)
|
1
2
3
4
5
6
|
#!/usr/bin/python
count =
0
while
(count <
9
):
print (count)
count = count +
1
print
"Good bye!"
|
while 語句時還有另外兩個重要的命令 continue,break 來跳過循環,continue 用於跳過該次循環,
break 則是用於退出循環,此外"判斷條件"還能夠是個常值,表示循環一定成立,具體用法以下:
1
2
3
4
5
6
7
8
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for
letter
in
'Python'
:
# 第一個實例
print
'當前字母 :'
, letter
fruits
=
[
'banana'
,
'apple'
,
'mango'
]
for
fruit
in
fruits:
# 第二個實例
print
'當前字母 :'
, fruit
print
"Good bye!"
|
無限循環
1
2
3
4
5
6
7
8
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for
letter
in
'Python'
:
# 第一個實例
print
'當前字母 :'
, letter
fruits
=
[
'banana'
,
'apple'
,
'mango'
]
for
fruit
in
fruits:
# 第二個實例
print
'當前字母 :'
, fruit
print
"Good bye!"
|
2.for循環
1
2
3
4
5
6
7
8
|
#!/usr/bin/python
# -*- coding: UTF-
8
-*-
for
letter
in
'Python'
: # 第一個實例
print
'當前字母 :'
, letter
fruits = [
'banana'
,
'apple'
,
'mango'
]
for
fruit
in
fruits: # 第二個實例
print
'當前字母 :'
, fruit
print
"Good bye!"
|
1
2
3
4
5
6
7
8
9
10
11
12
|
luckynum =
20
for
i
in
range(
3
):
input_num=
int
(input(
'please your lucky number:'
))
if
input_num == luckynum:
print(
'bingo'
)
break
elif input_num < luckynum:
print(
'please input big'
)
else
:
print(
'plase input small'
)
else
:
print(
'too many retrys'
)
|
二11、文件操做
打開文件:
1
|
file = open(
'文件路徑'
,
'模式'
)
|