例項教程:1小時學會Python
1 序言
面向讀者
本文適合有經驗的程式設計師儘快進入Python2.x世界.特別地,如果你掌握Java和Javascript,不用1小時你就可以用Python快速流暢地寫有用的Python程式.Python3.x使用者請參考:http://www.cnitblog.com/yunshichen/archive/2009/04/01/55924.html
(由於Django不支援python3, 所以為了你的發展潛力, 建議你學習python2.x)
為什麼使用Python
假設我們有這麼一項任務:簡單測試區域網中的電腦是否連通.這些電腦的ip範圍從192.168.0.101到192.168.0.200.思路:用shell程式設計.(Linux通常是bash而Windows是批處理指令碼).例如,在Windows上用ping ip 的命令依次測試各個機器並得到控制檯輸出.由於ping通的時候控制檯文字通常是"Reply from ... " 而不通的時候文字是"time out ... " ,所以,在結果中進行字串查詢,即可知道該機器是否連通.
實現:Java程式碼如下:
String cmd="cmd.exe ping ";
String ipprefix="192.168.10.";
int begin=101;
int end=200;
Process p=null;
for(int i=begin;i<end;i++){
p= Runtime.getRuntime().exec(cmd+i);
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = reader.readLine()) != null)
{
//Handling line , may logs it.
}
reader.close();
p.destroy();
}
String ipprefix="192.168.10.";
int begin=101;
int end=200;
Process p=null;
for(int i=begin;i<end;i++){
p= Runtime.getRuntime().exec(cmd+i);
String line = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = reader.readLine()) != null)
{
//Handling line , may logs it.
}
reader.close();
p.destroy();
}
這段程式碼執行得很好,問題是為了執行這段程式碼,你還需要做一些額外的工作.這些額外的工作包括:
- 編寫一個類檔案
- 編寫一個main方法
- 將之編譯成位元組程式碼
- 由於位元組程式碼不能直接執行,你需要再寫個小小的bat或者bash指令碼來執行.
同樣的工作用Python實現如下:
import subprocess
cmd="cmd.exe"
begin=101
end=200
while begin<end:
p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
p.stdin.write("ping 192.168.1."+str(begin)+"\n")
p.stdin.close()
p.wait()
print "execution result: %s"%p.stdout.read()
對比Java,Python的實現更為簡潔,你編寫的時間更快.你不需要寫main函式,並且這個程式儲存之後可以直接執行.另外,和Java一樣,Python也是跨平臺的.
有經驗的C/Java程式設計師可能會爭論說用C/Java寫會比Python寫得快.這個觀點見仁見智.我的想法是當你同時掌握Java和Python之後,你會發現用Python寫這類程式的速度會比Java快上許多.例如操作本地檔案時你僅需要一行程式碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應用範圍.用Python處理一些簡短程式類似與作業系統的互動程式設計工作最省時省力.
Python應用場合
足夠簡單的任務,例如一些shell程式設計.如果你喜歡用Python設計大型商業網站或者設計複雜的遊戲,悉聽尊便.2 快速入門
2.1 Hello world
安裝完Python之後(我本機的版本是2.5.4),開啟IDLE(Python GUI) , 該程式是Python語言直譯器,你寫的語句能夠立即執行.我們寫下一句著名的程式語句:
print "Hello,world!"
並按回車.你就能看到這句被K&R引入到程式世界的名言.
在直譯器中選擇"File"--"New Window" 或快捷鍵 Ctrl+N , 開啟一個新的編輯器.寫下如下語句:
print "Hello,world!"
raw_input("Press enter key to close this window");
raw_input("Press enter key to close this window");
儲存為a.py檔案.按F5,你就可以看到程式的執行結果了.這是Python的第二種執行方式.
找到你儲存的a.py檔案,雙擊.也可以看到程式結果.Python的程式能夠直接執行,對比Java,這是一個優勢.
2.2 國際化支援
我們換一種方式來問候世界.新建一個編輯器並寫如下程式碼:
print "歡迎來到奧運中國!"
raw_input("Press enter key to close this window");
raw_input("Press enter key to close this window");
在你儲存程式碼的時候,Python會提示你是否改變檔案的字符集,結果如下:
# -*- coding: cp936 -*-
print "歡迎來到奧運中國!"
raw_input("Press enter key to close this window");
print "歡迎來到奧運中國!"
raw_input("Press enter key to close this window");
將該字符集改為我們更熟悉的形式:
# -*- coding: GBK -*-
print "歡迎來到奧運中國!" # 使用中文的例子
raw_input("Press enter key to close this window");
print "歡迎來到奧運中國!" # 使用中文的例子
raw_input("Press enter key to close this window");
程式一樣執行良好.
2.3 方便易用的計算器
用微軟附帶的計算器來計數實在太麻煩了.開啟Python直譯器,直接進行計算:
a=100.0
b=201.1
c=2343
print (a+b+c)/c
b=201.1
c=2343
print (a+b+c)/c
2.4 字串,ASCII和UNICODE
可以如下列印出預定義輸出格式的字串:
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
字串是怎麼訪問的?請看這個例子:
word="abcdefg"
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]
print "e is: "+e # All elements of word.
f=word[-1]
print "f is: "+f # The last elements of word.
g=word[-4:-2]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "+h # The last two elements.
i=word[:-2]
print "i is: "+i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]
print "e is: "+e # All elements of word.
f=word[-1]
print "f is: "+f # The last elements of word.
g=word[-4:-2]
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "+h # The last two elements.
i=word[:-2]
print "i is: "+i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
請注意ASCII和UNICODE字串的區別:
print "Input your Chinese name:"
s=raw_input("Press enter to be continued");
print "Your name is : " +s;
l=len(s)
print "Length of your Chinese name in asc codes is:"+str(l);
a=unicode(s,"GBK")
l=len(a)
print "I'm sorry we should use unicode char!Characters number of your Chinese \
name in unicode is:"+str(l);
s=raw_input("Press enter to be continued");
print "Your name is : " +s;
l=len(s)
print "Length of your Chinese name in asc codes is:"+str(l);
a=unicode(s,"GBK")
l=len(a)
print "I'm sorry we should use unicode char!Characters number of your Chinese \
name in unicode is:"+str(l);
2.5 使用List
類似Java裡的List,這是一種方便易用的資料型別:
word=['a','b','c','d','e','f','g']
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "
print b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "
print c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "
print d # All elements of word.
e=word[:2]+word[2:]
print "e is: "
print e # All elements of word.
f=word[-1]
print "f is: "
print f # The last elements of word.
g=word[-4:-2]
print "g is: "
print g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "
print h # The last two elements.
i=word[:-2]
print "i is: "
print i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
print "Adds new element"
word.append('h')
print word
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: "
print b # index 1 and 2 elements of word.
c=word[:2]
print "c is: "
print c # index 0 and 1 elements of word.
d=word[0:]
print "d is: "
print d # All elements of word.
e=word[:2]+word[2:]
print "e is: "
print e # All elements of word.
f=word[-1]
print "f is: "
print f # The last elements of word.
g=word[-4:-2]
print "g is: "
print g # index 3 and 4 elements of word.
h=word[-2:]
print "h is: "
print h # The last two elements.
i=word[:-2]
print "i is: "
print i # Everything except the last two characters
l=len(word)
print "Length of word is: "+ str(l)
print "Adds new element"
word.append('h')
print word
2.6 條件和迴圈語句
# Multi-way decision
x=int(raw_input("Please enter an integer:"))
if x<0:
x=0
print "Negative changed to zero"
elif x==0:
print "Zero"
else:
print "More"
# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
x=int(raw_input("Please enter an integer:"))
if x<0:
x=0
print "Negative changed to zero"
elif x==0:
print "Zero"
else:
print "More"
# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
2.7 如何定義函式
# Define and invoke function.
def sum(a,b):
return a+b
func = sum
r = func(5,6)
print r
# Defines function with default argument
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r
def sum(a,b):
return a+b
func = sum
r = func(5,6)
print r
# Defines function with default argument
def add(a,b=2):
return a+b
r=add(1)
print r
r=add(1,5)
print r
並且,介紹一個方便好用的函式:
# The range() function
a =range(5,10)
print a
a = range(-2,-7)
print a
a = range(-7,-2)
print a
a = range(-2,-11,-3) # The 3rd parameter stands for step
print a
a =range(5,10)
print a
a = range(-2,-7)
print a
a = range(-7,-2)
print a
a = range(-2,-11,-3) # The 3rd parameter stands for step
print a
2.8 檔案I/O
spath="D:/download/baa.txt"
f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.
f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()
f=open(spath,"r") # Opens file for reading
for line in f:
print line
f.close()
f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.
f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()
f=open(spath,"r") # Opens file for reading
for line in f:
print line
f.close()
2.9 異常處理
s=raw_input("Input your age:")
if s =="":
raise Exception("Input must no be empty.")
try:
i=int(s)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unknown exception!"
else: # It is useful for code that must be executed if the try clause does not raise an exception
print "You are %d" % i," years old"
finally: # Clean up action
print "Goodbye!"
if s =="":
raise Exception("Input must no be empty.")
try:
i=int(s)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unknown exception!"
else: # It is useful for code that must be executed if the try clause does not raise an exception
print "You are %d" % i," years old"
finally: # Clean up action
print "Goodbye!"
2.10 類和繼承
class Base:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
# Child extends Base
class Child(Base):
def plus(self,a,b):
return a+b
oChild =Child()
oChild.add("str1")
print oChild.data
print oChild.plus(2,3)
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
# Child extends Base
class Child(Base):
def plus(self,a,b):
return a+b
oChild =Child()
oChild.add("str1")
print oChild.data
print oChild.plus(2,3)
2.11 包機制
每一個.py檔案稱為一個module,module之間可以互相匯入.請參看以下例子:
# a.py
def add_func(a,b):
return a+b
def add_func(a,b):
return a+b
# b.py
from a import add_func # Also can be : import a
print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2) # If using "import a" , then here should be "a.add_func"
from a import add_func # Also can be : import a
print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2) # If using "import a" , then here should be "a.add_func"
module可以定義在包裡面.Python定義包的方式稍微有點古怪,假設我們有一個parent資料夾,該資料夾有一個child子資料夾.child中有一個module a.py . 如何讓Python知道這個檔案層次結構?很簡單,每個目錄都放一個名為_init_.py 的檔案.該檔案內容可以為空.這個層次結構如下所示:
parent
--__init_.py
--child
-- __init_.py
--a.py
b.py
--__init_.py
--child
-- __init_.py
--a.py
b.py
那麼Python如何找到我們定義的module?在標準包sys中,path屬性記錄了Python的包路徑.你可以將之列印出來:
import sys
print sys.path
print sys.path
通常我們可以將module的包路徑放到環境變數PYTHONPATH中,該環境變數會自動新增到sys.path屬性.另一種方便的方法是程式設計中直接指定我們的module路徑到sys.path 中:
import sys
sys.path.append('D:\\download')
from parent.child.a import add_func
print sys.path
print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2)
sys.path.append('D:\\download')
from parent.child.a import add_func
print sys.path
print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2)
總結
你會發現這個教程相當的簡單.許多Python特性在程式碼中以隱含方式提出,這些特性包括:Python不需要顯式宣告資料型別,關鍵字說明,字串函式的解釋等等.我認為一個熟練的程式設計師應該對這些概念相當瞭解,這樣在你擠出寶貴的一小時閱讀這篇短短的教程之後,你能夠通過已有知識的遷移類比儘快熟悉Python,然後儘快能用它開始程式設計.當然,1小時學會Python頗有譁眾取寵之嫌.確切的說,程式語言包括語法和標準庫.語法相當於武術招式,而標準庫應用實踐經驗則類似於內功,需要長期鍛鍊.Python學習了Java的長處,提供了大量極方便易用的標準庫供程式設計師"拿來主義".(這也是Python成功的原因),在開篇我們看到了Python如何呼叫Windows cmd的例子,以後我會盡量寫上各標準庫的用法和一些應用技巧,讓大家真正掌握Python.
但不管怎樣,至少你現在會用Python代替繁瑣的批處理寫程式了.希望那些真的能在一小時內讀完本文並開始使用Python的程式設計師會喜歡這篇小文章,謝謝!
相關文章
- python例項1Python
- 一小時入門Python爬蟲,連我都會了!Python爬取租房資料例項Python爬蟲
- 1小時學會Git玩轉GitHubGithub
- Python學習:類和例項Python
- vue難學?1小時就能上手的教程Vue
- 跟著 AI 一個小時學會 PythonAIPython
- Java例項教程Java
- ORM 例項教程ORM
- Luat例項教程:adc
- 例項QT程式 —— Qt自繪製小時鐘QT
- python socket例項Python
- 深入 Laravel Nova 教程例項Laravel
- python鬧鐘例項Python
- python 類和例項Python
- python100例項Python
- Python例項集錦Python
- 閉包學習 1--例項分析 ComposerStaticInitxx::getInitializer
- python例項,python網路爬蟲爬取大學排名!Python爬蟲
- [轉載] Python 機器學習經典例項Python機器學習
- Python 3 學習筆記之類與例項Python筆記
- Web Components 入門例項教程Web
- 【FLASH例項1000教程】(4)上
- expand 與 unexpand 命令例項教程
- Python爬蟲教程-17-ajax爬取例項(豆瓣電影)Python爬蟲
- Python基礎——切片例項Python
- Debug和幾個小例項
- 人人都能學會的python程式設計教程14:高階特性1Python程式設計
- Makefile例項學習
- Python訪問小程式簡單方法程式碼例項詳解Python
- 微課|中學生可以這樣學Python(例11.1):tkinter電子時鐘程式(1)Python
- Luat例項教程:tcp短連線TCP
- 用鬥地主的例項學會使用java Collections工具類Java
- Python例項之用Python求完全平方數Python
- Python例項大全(基於Python3.7.4)Python
- python開發例項-python開發案例Python
- MySQL碎片整理小節--例項演示MySql
- python開發俄羅斯方塊小遊戲程式碼例項Python遊戲
- Python專案實戰例項Python
- 使用原生js實現選項卡功能例項教程JS