欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python基礎教程,Python入門教程(超詳細)

 更新時間:2021年06月23日 17:35:54   作者:不想禿頭的晨晨  
Python由荷蘭數(shù)學和計算機科學研究學會 于1990 年代初設計,作為一門叫做ABC語言的替代品。Python語法和動態(tài)類型,以及解釋型語言的本質(zhì),使它成為多數(shù)平臺上寫腳本和快速開發(fā)應用的編程語言

為什么使用Python

假設我們有這么一項任務:簡單測試局域網(wǎng)中的電腦是否連通.這些電腦的ip范圍從192.168.0.101到192.168.0.200.

思路:用shell編程.(Linux通常是bash而Windows是批處理腳本).例如,在Windows上用ping ip 的命令依次測試各個機器并得到控制臺輸出.由于ping通的時候控制臺文本通常是"Reply from … " 而不通的時候文本是"time out … " ,所以,在結(jié)果中進行字符串查找,即可知道該機器是否連通.

實現(xiàn):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方法
  • 將之編譯成字節(jié)代碼
  • 由于字節(jié)代碼不能直接運行,你需要再寫個小小的bat或者bash腳本來運行.

當然,用C/C++同樣能完成這項工作.但C/C++不是跨平臺語言.在這個足夠簡單的例子中也許看不出C/C++和Java實現(xiàn)的區(qū)別,但在一些更為復雜的場景,比如要將連通與否的信息記錄到網(wǎng)絡數(shù)據(jù)庫.由于Linux和Windows的網(wǎng)絡接口實現(xiàn)方式不同,你不得不寫兩個函數(shù)的版本.用Java就沒有這樣的顧慮.

同樣的工作用Python實現(xiàn)如下:

 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的實現(xiàn)更為簡潔,你編寫的時間更快.你不需要寫main函數(shù),并且這個程序保存之后可以直接運行.另外,和Java一樣,Python也是跨平臺的.

有經(jīng)驗的C/Java程序員可能會爭論說用C/Java寫會比Python寫得快.這個觀點見仁見智.我的想法是當你同時掌握Java和Python之后,你會發(fā)現(xiàn)用Python寫這類程序的速度會比Java快上許多.例如操作本地文件時你僅需要一行代碼而不需要Java的許多流包裝類.各種語言有其天然的適合的應用范圍.用Python處理一些簡短程序類似與操作系統(tǒng)的交互編程工作最省時省力.

Python應用場合

足夠簡單的任務,例如一些shell編程.如果你喜歡用Python設計大型商業(yè)網(wǎng)站或者設計復雜的游戲,悉聽尊便.

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,你就可以看到程序的運行結(jié)果了.這是Python的第二種運行方式.

找到你保存的a.py文件,雙擊.也可以看到程序結(jié)果.Python的程序能夠直接運行,對比Java,這是一個優(yōu)勢.

國際化支持

我們換一種方式來問候世界.新建一個編輯器并寫如下代碼:

print "歡迎來到奧運中國!" 
raw_input("Press enter key to close this window!");

在你保存代碼的時候,Python會提示你是否改變文件的字符集,結(jié)果如下:

# -*- coding: cp936 -*-
print "歡迎來到奧運中國!" 
raw_input("Press enter key to close this window! ");

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

# -*- coding: GBK -*-
print "歡迎來到奧運中國!" # 使用中文的例子 
raw_input("Press enter key to close this window");

程序一樣運行良好.

便易用的計算器

用微軟附帶的計算器來計數(shù)實在太麻煩了.打開Python解釋器,直接進行計算:

a=100.0 
b=201.1 
c=2343 
print (a+b+c)/c 

字符串,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字符串的區(qū)別:

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);

使用List

類似Java里的List,這是一種方便易用的數(shù)據(jù)類型:

word=['a','b','c','d','e','f','g']
a=word[2]
print "a is: "+a
b=word[1:3]
print "b is: " print b # index1 and 2 elements of word.
c=word[:2]
print "c is: " print c # index0 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 # index3 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[圖片上傳中...(image-b4ced-1616074265420-0)] " word.append('h')
print word

條件和循環(huán)語句

# 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 ina:
    print x, len(x) 

如何定義函數(shù)

# 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

并且,介紹一個方便好用的函數(shù):

# 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

文件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 forreading 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!"

類和繼承

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)

包機制

每一個.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知道這個文件層次結(jié)構(gòu)?很簡單,每個目錄都放一個名為_init_.py 的文件.該文件內(nèi)容可以為空.這個層次結(jié)構(gòu)如下所示:

parent 
  --__init_.py
  --child
    -- __init_.py
    --a.py
b.py

那么Python如何找到我們定義的module?在標準包sys中,path屬性記錄了Python的包路徑.你可以將之打印出來:

import sys
print sys.path

通常我們可以將module的包路徑放到環(huán)境變量PYTHONPATH中,該環(huán)境變量會自動添加到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)

總結(jié)

你會發(fā)現(xiàn)這個教程相當?shù)暮唵?許多Python特性在代碼中以隱含方式提出,這些特性包括:Python不需要顯式聲明數(shù)據(jù)類型,關鍵字說明,字符串函數(shù)的解釋等等.我認為一個熟練的程序員應該對這些概念相當了解,這樣在你擠出寶貴的一小時閱讀這篇短短的教程之后,你能夠通過已有知識的遷移類比盡快熟悉Python,然后盡快能用它開始編程.

本篇文章就到這里了,希望能給大家?guī)韼椭?,也希望大家能夠多多關注腳本之家的更多內(nèi)容!

相關文章

  • python Matplotlib基礎--如何添加文本和標注

    python Matplotlib基礎--如何添加文本和標注

    這篇文章主要介紹了python Matplotlib基礎--如何添加文本和標注,幫助大家更好的利用Matplotlib繪制圖表,感興趣的朋友可以了解下
    2021-01-01
  • python 日志模塊logging的使用場景及示例

    python 日志模塊logging的使用場景及示例

    這篇文章主要介紹了python 日志模塊logging的使用場景及示例,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2021-01-01
  • Python使用中文正則表達式匹配指定中文字符串的方法示例

    Python使用中文正則表達式匹配指定中文字符串的方法示例

    這篇文章主要介紹了Python使用中文正則表達式匹配指定中文字符串的方法,結(jié)合實例形式分析了Python正則匹配及字符編碼相關操作技巧,需要的朋友可以參考下
    2017-01-01
  • PyTorch模型保存與加載實例詳解

    PyTorch模型保存與加載實例詳解

    大家都知道pytorch的模型和參數(shù)是分開的,可以分別保存或加載模型和參數(shù),這篇文章主要給大家介紹了關于PyTorch模型保存與加載的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • 利用?Python?讓圖表動起來

    利用?Python?讓圖表動起來

    這篇文章主要給大家分享如何利用?Python?讓圖表動起來,本文圍繞Python?讓圖表動起來的話題舉例matplotlib動畫功能的一個例子展開文章內(nèi)容,需要的朋友可以參考一下
    2021-10-10
  • Python處理字符串中文(漢字)編碼的實例

    Python處理字符串中文(漢字)編碼的實例

    這篇文章主要介紹了Python處理字符串中文(漢字)編碼的實例,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • django model去掉unique_together報錯的解決方案

    django model去掉unique_together報錯的解決方案

    本文給大家分享的是在使用django model去掉unique_together時報錯的解決思路和具體步驟,提供給大家參考下,希望對大家學習使用django能夠有所幫助
    2016-10-10
  • Python字符串str超詳細詳解(適合新手!)

    Python字符串str超詳細詳解(適合新手!)

    str函數(shù)是Python的內(nèi)置函數(shù),它將參數(shù)轉(zhuǎn)換成字符串類型,即人適合閱讀的形式,下面這篇文章主要給大家介紹了關于Python字符串str超詳細詳解的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-11-11
  • 深入理解Playwright的高級功能和用法

    深入理解Playwright的高級功能和用法

    Playwright是一個強大而靈活的Python庫,用于自動化瀏覽器操作和測試,本文主要介紹了深入理解Playwright的高級功能和用法,具有一定的 參考價值,感興趣的可以了解一下
    2024-05-05
  • 整理Python中常用的conda命令操作

    整理Python中常用的conda命令操作

    今天給大家?guī)淼氖顷P于Python的相關知識,文章圍繞著Python中常用的conda命令行操作展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06

最新評論