本節內容2016-05-30php
1、Ptyhon介紹html
Python誕生於1989年聖誕節期間,創始人吉多•範羅蘇姆(Guido Van Gossum)。java
最新TIOBE排行榜(http://www.tiobe.com/tiobe_index?page=index),Python趕超PHP佔據第五,Python崇尚優美、清晰、簡單,是一個優秀並普遍使用的語言。python
Python能夠應用於衆多領域:數據分析、組件集成、網絡服務、圖像處理、數值計算和科室計算等。linux
目前幾乎全部在中型互聯網企業都在使用Pthon:Youtube、Dropbox、BT、Quora(中國知乎)、Google、Yahoo!、Facebook、NASA、百度、騰訊、汽車之家、美團等。ios
目前Python主要應用領域:c++
Python在一些公司的應用: web
爲何是Python而不是其餘語言?算法
C 和 Python、Java、C#等shell
C語言: 代碼編譯獲得 機器碼 ,機器碼在處理器上直接執行,每一條指令控制CPU工做
其餘語言: 代碼編譯獲得 字節碼 ,虛擬機執行字節碼並轉換成機器碼再後在處理器上執行
Python 和 C Python這門語言是由C開發而來
對於使用:Python的類庫齊全而且使用簡潔,若是要實現一樣的功能,Python 10行代碼能夠解決,C可能就須要100行甚至更多.
對於速度:Python的運行速度相較與C,絕逼是慢了
Python 和 Java、C#等
對於使用:Linux原裝Python,其餘語言沒有;以上幾門語言都有很是豐富的類庫支持
對於速度:Python在速度上可能稍顯遜色
因此,Python和其餘語言沒有什麼本質區別,其餘區別在於:擅長某領域、人才豐富、先入爲主。
Python的種類
Python的官方版本,使用C語言實現,使用最爲普遍,CPython實現會將源文件(py文件)轉換成字節碼文件(pyc文件),而後運行在Python虛擬機上。
Python的Java實現,Jython會將Python代碼動態編譯成Java字節碼,而後在JVM上運行。
Python的C#實現,IronPython將Python代碼編譯成C#字節碼,而後在CLR上運行。(與Jython相似)
Python實現的Python,將Python的字節碼字節碼再編譯成機器碼。
In summary : Python 2.x is legacy, Python 3.x is the present and future of the language
Python 3.0 was released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of
extended support for this end-of-life release. The 2.x branch will see no new major releases after that. 3.x is
under active development and has already seen over five years of stable releases, including version 3.3 in 2012,
3.4 in 2014, and 3.5 in 2015. This means that all recent standard library improvements, for example, are only
available by default in Python 3.x.
Guido van Rossum (the original creator of the Python language) decided to clean up Python 2.x properly, with less regard for backwards compatibility than is the case for new releases in the 2.x range. The most drastic improvement is the better Unicode support (with all text strings being Unicode by default) as well as saner bytes/Unicode separation.
Besides, several aspects of the core language (such as print and exec being statements, integers using floor division) have been adjusted to be easier for newcomers to learn and to be more consistent with the rest of the language, and old cruft has been removed (for example, all classes are now new-style, "range()" returns a memory efficient iterable, not a list as in 2.x).
PRINT IS A FUNCTION
The statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old statement (PEP 3105). Examples:
1 Old: print "The answer is", 2*2 New: print("The answer is", 2*2) 2 Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline 3 Old: print # Prints a newline 4 New: print() # You must call the function! 5 Old: print >>sys.stderr, "fatal error" New: print("fatal error", file=sys.stderr) 6 Old: print (x, y) # prints repr((x, y)) 7 New: print((x, y)) # Not the same as print(x, y)!
You can also customize the separator between items, e.g.:
1 print("There are <", 2**32, "> possibilities!", sep="")
ALL IS UNICODE NOW
還能夠這樣玩: (A,*REST,B)=RANGE(5)
1 <strong>>>> a,*rest,b = range(5) 2 >>> a,rest,b 3 (0, [1, 2, 3], 4) 4 </strong>
某些庫更名了
Old Name |
New Name |
_winreg |
winreg |
ConfigParser |
configparser |
copy_reg |
copyreg |
Queue |
queue |
SocketServer |
socketserver |
markupbase |
_markupbase |
repr |
reprlib |
test.test_support |
test.support |
還有誰不支持PYTHON3?
One popular module that don't yet support Python 3 is Twisted (for networking and other applications). Most
actively maintained libraries have people working on 3.x support. For some libraries, it's more of a priority than
others: Twisted, for example, is mostly focused on production servers, where supporting older versions of
Python is important, let alone supporting a new version that includes major changes to the language. (Twisted is
a prime example of a major package where porting to 3.x is far from trivial
1、下載安裝包 https://www.python.org/downloads/ 2、安裝 默認安裝路徑:C:\python27 3、配置環境變量 【右鍵計算機】--》【屬性】--》【高級系統設置】--》【高級】--》【環境變量】--》【在第二個內容框中找到 變量名爲Path 的一行,雙擊】 --> 【Python安裝目錄追加到變值值中,用 ; 分割】 如:原來的值;C:\python27,切記前面有分號
linux、Mac
無需安裝,原裝Python環境 ps:若是自帶2.6,請更新至2.7
在linux 下建立一個文件叫hello.py,並輸入
print("Hello world!")
而後執行命令:python hello.py ,輸出
$ vim hello.py
$ python hello.py
Hello world!
如此一來,執行: ./hello.py
便可。
ps:執行前需給予 hello.py 執行權限,chmod 755 hello.py
1 [root@test ~]# python 2 Python 2.7.11 (default, May 17 2016, 14:00:45) 3 [GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2 4 Type "help", "copyright", "credits" or "license" for more information. 5 >>> print("Hello world!") 6 Hello world!
對比下其它語言的hello world
1 #include <iostream> 2 int main(void) 3 { 4 std::cout<<"Hello world"; 5 }
1 #include <stdio.h> 2 int main(void) 3 { 4 printf("\nhello world!"); 5 return 0; 6 }
1 public class HelloWorld{ 2 // 程序的入口 3 public static void main(String args[]){ 4 // 向控制檯輸出信息 5 System.out.println("Hello World!"); 6 } 7 }
1 <?php 2 echo "hello world!"; 3 ?>
1 puts "Hello world."
1 package main 2 3 import "fmt" 4 5 func main(){ 6 7 fmt.Printf("Hello World!\n God Bless You!"); 8 9 }
Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.
聲明變量
#_*_coding:utf-8_*_ name = "Shawn Yu"
上述代碼聲明瞭一個變量,變量名爲: name,變量name的值爲:"Shawn Yu"
變量定義的規則:
name = "Shawn Li" name2 = name print(name,name2) name = "Jack" print("What is the value of name2 now?")
python解釋器在加載 .py 文件中的代碼時,會對內容進行編碼(默認ascill)
ASCII(American Standard Code for Information Interchange,美國標準信息交換代碼)是基於拉丁字母的一套電腦編碼系統,主要用於顯示現代英語和其餘西歐語言,其最多隻能用 8 位來表示(一個字節),即:2**8 = 256-1,因此,ASCII碼最多隻能表示 255 個符號。
顯然ASCII碼沒法將世界上的各類文字和符號所有表示,因此,就須要新出一種能夠表明全部字符和符號的編碼,即:Unicode
Unicode(統一碼、萬國碼、單一碼)是一種在計算機上使用的字符編碼。Unicode 是爲了解決傳統的字符編碼方案的侷限而產生的,它爲每種語言中的每一個字符設定了統一而且惟一的二進制編碼,規定雖有的字符和符號最少由 16 位來表示(2個字節),即:2 **16 = 65536,
注:此處說的的是最少2個字節,可能更多
UTF-8,是對Unicode編碼的壓縮和優化,他再也不使用最少使用2個字節,而是將全部的字符和符號進行分類:ascii碼中的內容用1個字節保存、歐洲的字符用2個字節保存,東亞的字符用3個字節保存...
因此,python解釋器在加載 .py 文件中的代碼時,會對內容進行編碼(默認ascill),若是是以下代碼的話:
報錯:ascii碼沒法表示中文
1 #!/usr/bin/env python 2 3 print "你好,世界"
改正:應該顯示的告訴python解釋器,用什麼編碼來執行源代碼,即:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 print "你好,世界"
當行注視:# 被註釋內容
多行註釋:""" 被註釋內容 """
1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 4 5 #name = raw_input("What is your name?") #only on python 2.x 6 name = input("What is your name?") 7 print("Hello " + name )
輸入密碼時,若是想要不可見,須要利用getpass 模塊中的 getpass方法,即:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import getpass 5 6 # 將用戶輸入的內容賦值給 name 變量 7 pwd = getpass.getpass("請輸入密碼:") 8 9 # 打印輸入的內容 10 print(pwd)
Python的強大之處在於他有很是豐富和強大的標準庫和第三方庫,幾乎你想實現的任何功能都有相應的Python庫支持,之後的課程中會深刻講解經常使用到的各類庫,如今,咱們先來象徵性的學2個簡單的。
sys
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import sys 5 6 print(sys.argv) 7 8 9 #輸出 10 $ python test.py helo world 11 ['test.py', 'helo', 'world'] #把執行腳本時傳遞的參數獲取到了
os
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import os 5 6 os.system("df -h") #調用系統命令
徹底結合一下
1 import os,sys 2 3 os.system(''.join(sys.argv[1:])) #把用戶的輸入的參數看成一條命令交給os.system來執
本身寫個模塊
python tab補全模塊
1. Python是一門解釋型語言?
我初學Python時,聽到的關於Python的第一句話就是,Python是一門解釋性語言,我就這樣一直相信下去,直到發現了*.pyc文件的存在。若是是解釋型語言,那麼生成的*.pyc文件是什麼呢?c應該是compiled的縮寫纔對啊!
爲了防止其餘學習Python的人也被這句話誤解,那麼咱們就在文中來澄清下這個問題,而且把一些基礎概念給理清。
2. 解釋型語言和編譯型語言
計算機是不可以識別高級語言的,因此當咱們運行一個高級語言程序的時候,就須要一個「翻譯機」來從事把高級語言轉變成計算機能讀懂的機器語言的過程。這個過程分紅兩類,第一種是編譯,第二種是解釋。
編譯型語言在程序執行以前,先會經過編譯器對程序執行一個編譯的過程,把程序轉變成機器語言。運行時就不須要翻譯,而直接執行就能夠了。最典型的例子就是C語言。
解釋型語言就沒有這個編譯的過程,而是在程序運行的時候,經過解釋器對程序逐行做出解釋,而後直接運行,最典型的例子是Ruby。
經過以上的例子,咱們能夠來總結一下解釋型語言和編譯型語言的優缺點,由於編譯型語言在程序運行以前就已經對程序作出了「翻譯」,因此在運行時就少掉了「翻譯」的過程,因此效率比較高。可是咱們也不能一律而論,一些解釋型語言也能夠經過解釋器的優化來在對程序作出翻譯時對整個程序作出優化,從而在效率上超過編譯型語言。
此外,隨着Java等基於虛擬機的語言的興起,咱們又不能把語言純粹地分紅解釋型和編譯型這兩種。
用Java來舉例,Java首先是經過編譯器編譯成字節碼文件,而後在運行時經過解釋器給解釋成機器文件。因此咱們說Java是一種先編譯後解釋的語言。
3. Python究竟是什麼
其實Python和Java/C#同樣,也是一門基於虛擬機的語言,咱們先來從表面上簡單地瞭解一下Python程序的運行過程吧。
當咱們在命令行中輸入python hello.py時,實際上是激活了Python的「解釋器」,告訴「解釋器」:你要開始工做了。但是在「解釋」以前,其實執行的第一項工做和Java同樣,是編譯。
熟悉Java的同窗能夠想一下咱們在命令行中如何執行一個Java的程序:
javac hello.java
java hello
只是咱們在用Eclipse之類的IDE時,將這兩部給融合成了一部而已。其實Python也同樣,當咱們執行python hello.py時,他也同樣執行了這麼一個過程,因此咱們應該這樣來描述Python,Python是一門先編譯後解釋的語言。
4. 簡述Python的運行過程
在說這個問題以前,咱們先來講兩個概念,PyCodeObject和pyc文件。
咱們在硬盤上看到的pyc天然沒必要多說,而其實PyCodeObject則是Python編譯器真正編譯成的結果。咱們先簡單知道就能夠了,繼續向下看。
當python程序運行時,編譯的結果則是保存在位於內存中的PyCodeObject中,當Python程序運行結束時,Python解釋器則將PyCodeObject寫回到pyc文件中。
當python程序第二次運行時,首先程序會在硬盤中尋找pyc文件,若是找到,則直接載入,不然就重複上面的過程。
因此咱們應該這樣來定位PyCodeObject和pyc文件,咱們說pyc文件實際上是PyCodeObject的一種持久化保存方式。
2 是一個整數的例子。
長整數 不過是大一些的整數。
3.23和52.3E-4是浮點數的例子。E標記表示10的冪。在這裏,52.3E-4表示52.3 * 10-4。
(-5+4j)和(2.3-4.6j)是複數的例子。
int(整型)
"hello world"
1 name = "shawn" 2 print "i am %s " % name 3 4 #輸出: i am shawn
PS: 字符串是 %s;整數 %d;浮點數%f
1 name_list = ['alex', 'seven', 'eric'] 2 或 3 name_list = list(['alex', 'seven', 'eric'])
基本操做:
1 ages = (11, 22, 33, 44, 55) 2 或 3 ages = tuple((11, 22, 33, 44, 55))
1 person = {"name": "mr.wu", 'age': 18} 2 或 3 person = dict({"name": "mr.wu", 'age': 18})
經常使用操做:
場景1、用戶登錄驗證
1 # 提示輸入用戶名和密碼 2 3 # 驗證用戶名和密碼 4 # 若是錯誤,則輸出用戶名或密碼錯誤 5 # 若是成功,則輸出 歡迎,XXX! 6 7 8 #!/usr/bin/env python 9 # -*- coding: encoding -*- 10 11 import getpass 12 13 14 name = raw_input('請輸入用戶名:') 15 pwd = getpass.getpass('請輸入密碼:') 16 17 if name == "alex" and pwd == "cmd": 18 print("歡迎,alex!") 19 else: 20 print("用戶名和密碼錯誤")
場景2、猜年齡遊戲
在程序裏設定好你的年齡,而後啓動程序讓用戶猜想,用戶輸入後,根據他的輸入提示用戶輸入的是否正確,若是錯誤,提示是猜大了仍是小了
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 5 my_age = 28 6 7 user_input = int(input("input your guess num:")) 8 9 if user_input == my_age: 10 print("Congratulations, you got it !") 11 elif user_input < my_age: 12 print("Oops,think bigger!") 13 else: 14 print("think smaller!")
最簡單的循環10次
1 #_*_coding:utf-8_*_ 2 __author__ = 'Alex Li' 3 4 5 for i in range(10): 6 print("loop:", i )
輸出:
1 loop: 0 2 loop: 1 3 loop: 2 4 loop: 3 5 loop: 4 6 loop: 5 7 loop: 6 8 loop: 7 9 loop: 8 10 loop: 9
需求一:仍是上面的程序,可是遇到小於5的循環次數就不走了,直接跳入下一次循環
1 for i in range(10): 2 if i<5: 3 continue #不往下走了,直接進入下一次loop 4 print("loop:", i )
需求二:仍是上面的程序,可是遇到大於5的循環次數就不走了,直接退出
1 for i in range(10): 2 if i>5: 3 break #不往下走了,直接跳出整個loop 4 print("loop:", i )
有一種循環叫死循環,一經觸發,就運行個天荒地老、海枯石爛。
海枯石爛代碼
1 count = 0 2 while True: 3 print("你是風兒我是沙,纏纏綿綿到天涯...",count) 4 count +=1
其實除了時間,沒有什麼是永恆的,死loop仍是少寫爲好
上面的代碼循環100次就退出吧
1 count = 0 2 while True: 3 print("你是風兒我是沙,纏纏綿綿到天涯...",count) 4 count +=1 5 if count == 100: 6 print("去你媽的風和沙,大家這些脫了褲子是人,穿上褲子是鬼的臭男人..") 7 break
回到上面for 循環的例子,如何實現讓用戶不斷的猜年齡,但只給最多3次機會,再猜不對就退出程序。
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 5 my_age = 28 6 7 count = 0 8 while count < 3: 9 user_input = int(input("input your guess num:")) 10 11 if user_input == my_age: 12 print("Congratulations, you got it !") 13 break 14 elif user_input < my_age: 15 print("Oops,think bigger!") 16 else: 17 print("think smaller!") 18 count += 1 #每次loop 計數器+1 19 else: 20 print("猜這麼屢次都不對,你個笨蛋.")