首頁  >  文章  >  後端開發  >  為什麼用Python及Python快速入門教程

為什麼用Python及Python快速入門教程

Y2J
Y2J原創
2017-04-18 17:58:361314瀏覽

1 為什麼要使用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();
}


    這段程式碼運作得很好,問題是為了運行這段程式碼,你還需要做一些額外的工作.這些額外的工作包括:

  • #寫一個類別檔案

  • 寫一個main方法

  • 將之編譯成位元組程式碼

  • 由於字節程式碼不能直接運作,你需要再寫一個小小的bat或bash腳本來運行.

    當然,用C/C++同樣能完成這項工作.但C/C++不是跨平台語言.在這個足夠簡單的例子中也許看不出C/C++和Java實現的區別,但在一些更為複雜的場景,比如要將連通與否的資訊記錄到網路資料庫.由於Linux和Windows的網路介面實作方式不同,你不得不寫兩個函數的版本.用Java就沒有這樣的顧慮.

    同樣的工作用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");

    儲存為a.py檔.按F5,你就可以看到程式的運作結果了.這是Python的第二種運作方式.

    找到你保存的a.py檔案,雙擊.也可以看到程式結果.Python的程式能夠直接運作,對比Java,這是一個優點.


2.2 國際化支援
    我們換個方式來問候世界.新建一個編輯器並寫如下程式碼:


print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");

#    在你儲存程式碼的時候,Python會提示你是否改變文件的字符集,結果如下:


# -*- coding: cp936 -*- 
print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window");

    將該字符集改為我們更熟悉的形式:

#

# -*- coding: GBK -*- 
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


2.4 字串,ASCII和UNICODE

    可以如下列印出預先定義輸出格式的字串:

print """
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)

    請注意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&#39;m sorry we should use unicode char!Characters number of your Chinese \
name in unicode is:"+str(l);


2.5 使用List

    類似Java裡的List,這是一個方便易用的

資料型別:
#

word=[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;]
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(&#39;h&#39;)
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 = [&#39;cat&#39;, &#39;window&#39;, &#39;defenestrate&#39;]
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

    並且,介紹一個方便好用的函數:

# 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


2.8 文件I/O
spath="D:/download/baa.txt"
f=open(spath,"w") # Opens file for writing.Creates this file doesn&#39;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!"

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)

2.11 包机制

    每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子:

# a.py
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"



    module可以定义在包里面.Python定义包的方式稍微有点古怪,假设我们有一个parent文件夹,该文件夹有一个child子文件夹.child中有一个module a.py . 如何让Python知道这个文件层次结构?很简单,每个目录都放一个名为_init_.py 的文件.该文件内容可以为空.这个层次结构如下所示: 

parent 
  --init_.py
  --child
    -- init_.py
    --a.py
b.py


    那么Python如何找到我们定义的module?在标准包sys中,path属性记录了Python的包路径.你可以将之打印出来:

import sys
print sys.path


    通常我们可以将module的包路径放到环境变量PYTHONPATH中,该环境变量会自动添加到sys.path属性.另一种方便的方法是编程中直接指定我们的module路径到sys.path 中:

import sys
sys.path.append(&#39;D:\\download&#39;)
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快速入門教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn