目錄
為什麼使用Python
Python應用場合
2 快速入門
2.1 Hello world
2.2 國際化支援
2.3 方便易用的計算器
%%PRE_BLOCK_13%%

%%PRE_BLOCK_17%%
总结
首頁 後端開發 Python教學 Python入門教學 詳細1小時學會Python_python

Python入門教學 詳細1小時學會Python_python

May 30, 2018 pm 02:50 PM
python 入門教學 學會

本文適合有經驗的程式設計師盡快進入Python世界.特別地,如果你掌握Java和Javascript,不用1小時你就可以用Python快速流暢地寫有用的Python程式.

為什麼使用Python

假設我們有這麼多任務:簡單測試區域網路中的電腦是否連通.這些電腦的ip範圍從192.168.0.101到192.168.0.200.  
    想法:用shell程式設計.(Linux通常程式設計.(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的程序员会喜欢这篇小文章,谢谢!

相关推荐:

python入门教程之列表操作

一篇不错的Python入门教程

简洁的十分钟Python入门教程



以上是Python入門教學 詳細1小時學會Python_python的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP教程
1596
276
如何在Sublime文本中調試Python代碼? 如何在Sublime文本中調試Python代碼? Aug 14, 2025 pm 04:51 PM

UseSublimeText’sbuildsystemtorunPythonscriptsandcatcherrorsbypressingCtrl Baftersettingthecorrectbuildsystemorcreatingacustomone.2.Insertstrategicprint()statementstocheckvariablevalues,types,andexecutionflow,usinglabelsandrepr()forclarity.3.Installth

如何在Sublime文本中運行Python代碼? 如何在Sublime文本中運行Python代碼? Aug 16, 2025 am 04:58 AM

確保已安裝Python並將其添加到系統PATH,通過終端運行python--version或python3--version驗證;2.將Python文件保存為.py擴展名,如hello.py;3.在SublimeText中創建自定義構建系統,Windows用戶使用{"cmd":["python","-u","$file"]},macOS/Linux用戶使用{"cmd":["python3

如何在VScode中調試Python腳本 如何在VScode中調試Python腳本 Aug 16, 2025 am 02:53 AM

要調試Python腳本,需先安裝Python擴展並配置解釋器,然後創建launch.json文件設置調試配置,接著在代碼中設置斷點並按F5啟動調試,腳本將在斷點處暫停,允許檢查變量和單步執行,最終通過查看控制台輸出、添加日誌或調整參數等方式排查問題,確保環境正確後調試過程簡單高效。

如何在VSCODE中自動格式化Python代碼 如何在VSCODE中自動格式化Python代碼 Aug 14, 2025 pm 04:10 PM

toAutomation formatemationalformatpytpythoncodeinvscode,installblackusingpipinstallblack,installtheofficialmicrosoftpythonextension,setblackastheformatterinsettings.jsonwith“ python.formatting.formatting.provider”

Python中的類方法是什麼 Python中的類方法是什麼 Aug 21, 2025 am 04:12 AM

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

收益率關鍵字如何在Python中起作用 收益率關鍵字如何在Python中起作用 Aug 15, 2025 am 08:23 AM

yield關鍵字用於定義生成器函數,使其能暫停執行並逐個返回值,之後從暫停處恢復;生成器函數返回生成器對象,具有惰性求值特性,可節省內存,適用於處理大文件、流數據和無限序列等場景,且生成器是迭代器,支持next()和for循環,但無法倒回,必須重新創建才能再次迭代。

python asyncio隊列示例 python asyncio隊列示例 Aug 21, 2025 am 02:13 AM

asyncio.Queue是用於異步任務間安全通信的隊列工具,1.生產者通過awaitqueue.put(item)添加數據,消費者用awaitqueue.get()獲取數據;2.每處理完一項需調用queue.task_done(),以便queue.join()等待所有任務完成;3.使用None作為結束信號通知消費者停止;4.多個消費者時,需發送多個結束信號或在取消任務前確保所有任務已處理完畢;5.隊列支持設置maxsize限制容量,put和get操作自動掛起不阻塞事件循環,程序最終通過canc

如何在Sublime文本中創建一個Python項目? 如何在Sublime文本中創建一個Python項目? Aug 16, 2025 am 08:53 AM

InstallSublimeTextandPython,thenconfigureabuildsystembycreatingaPython3.sublime-buildfilewiththeappropriatecmdandselectorsettingstoenablerunningPythonscriptsviaCtrl B.2.OrganizeyourprojectbycreatingadedicatedfolderwithPythonfilesandsupportingdocument

See all articles