本文參考:http://www.jb51.net/article/926.htm 點擊打開鏈接
本人將會對它進行進行一步補充,使其更完整、易讀。
快速入門
安裝完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,這是一個優勢.
我們換一種方式來問候世界.新建一個編輯器並寫如下代碼:
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");
程序一樣運行良好.
用微軟附帶的計算器來計數實在太麻煩了.打開Python解釋器,直接進行計算:
a=100.0
b=201.1
c=2343
print (a+b+c)/c
b=201.1
c=2343
print (a+b+c)/c
可以如下打印出預定義輸出格式的字符串:
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);
類似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
# 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)
# 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
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()
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!"
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)
每一個.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的程序員會喜歡這篇小文章,謝謝!