本文執行個體講述了Python簡明入門教程。分享給大家供大家參考。具體如下:
一、基本概念
1、數
在Python中有4種類型的數——整數、長整數、浮點數和複數。
(1)2是一個整數的例子。
(2)長整數不過是大一些的整數。
(2)3.23和52.3E-4是浮點數的例子。E標記表示10的冪。在這裡,52.3E-4表示52.3 * 10-4。
(4)(-5+4j)和(2.3-4.6j)是複數的例子。
2、字串
(1)使用單引號(')
(2)使用雙引號(")
(3)使用三引號('''或""")
利用三引號,你可以指示一個多行的字串。你可以在三引號中自由的使用單引號和雙引號。例如:
'''This is a multi-line string. This is the first line.This is the second line."What's your name?," I asked.He said "Bond, James Bond."'''
(4)轉義符
(5)自然字串
自然字串通過給字串加上首碼r或R來指定。例如r"Newlines are indicated by \n"。
3、邏輯行與物理行
一個物理行中使用多於一個邏輯行,需要使用分號(;)來特別地標明這種用法。一個物理行只有一個邏輯行可不用分號
二、控制流程
1、if
塊中不用大括弧,條件後用分號,對應elif和else
if guess == number: print 'Congratulations, you guessed it.' # New block starts hereelif guess < number: print 'No, it is a little higher than that' # Another blockelse: print 'No, it is a little lower than that'
2、while
用分號,可搭配else
while running: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that' else: print 'No, it is a little lower than that'else: print 'The while loop is over.' # Do anything else you want to do here
3、for
用分號,搭配else
for i in range(1, 5): print ielse: print 'The for loop is over'
4、break和continue
同C語言
三、函數
1、定義與調用
def sayHello(): print 'Hello World!' # block belonging to the functionsayHello() # call the function
2、函數形參
類C語言
def printMax(a, b): if a > b: print a, 'is maximum' else: print b, 'is maximum'
3、局部變數
加global可申明為全域變數
4、預設參數值
def say(message, times = 1): print message * times
5、關鍵參數
如果某個函數有許多參數,而只想指定其中的一部分,那麼可以通過命名來為這些參數賦值——這被稱作 關鍵參數 ——使用名字(關鍵字)而不是位置來給函數指定實參。這樣做有兩個 優勢 ——一,由於不必擔心參數的順序,使用函數變得更加簡單了。二、假設其他參數都有預設值,可以只給我們想要的那些參數賦值。
def func(a, b=5, c=10): print 'a is', a, 'and b is', b, 'and c is', cfunc(3, 7)func(25, c=24)func(c=50, a=100)
6、return
四、模組
1、使用模組
import sysprint 'The command line arguments are:'for i in sys.argv: print i
如果想要直接輸入argv變數到程式中(避免在每次使用它時打sys.),可以使用from sys import argv語句
2、dir()函數
可以使用內建的dir函數來列出模組定義的標識符。標識符有函數、類和變數。
五、資料結構
1、列表
shoplist = ['apple', 'mango', 'carrot', 'banana']print 'I have', len(shoplist),'items to purchase.'print 'These items are:', # Notice the comma at end of the linefor item in shoplist: print item,print '\nI also have to buy rice.'shoplist.append('rice')print 'My shopping list is now', shoplistprint 'I will sort my list now'shoplist.sort()print 'Sorted shopping list is', shoplistprint 'The first item I will buy is', shoplist[0]olditem = shoplist[0]del shoplist[0]print 'I bought the', olditemprint 'My shopping list is now', shoplist
2、元組
元組和列表十分類似,只不過元組和字串一樣是不可變的即你不能修改元組。
zoo = ('wolf', 'elephant', 'penguin')print 'Number of animals in the zoo is', len(zoo)new_zoo = ('monkey', 'dolphin', zoo)print 'Number of animals in the new zoo is', len(new_zoo)print 'All animals in new zoo are', new_zooprint 'Animals brought from old zoo are', new_zoo[2]print 'Last animal brought from old zoo is', new_zoo[2][2]
像一棵樹
元組與列印
age = 22name = 'Swaroop'print '%s is %d years old' % (name, age)print 'Why is %s playing with that python?' % name
3、字典
類似雜湊
ab = { 'Swaroop' : 'swaroopch@byteofpython.info', 'Larry' : 'larry@wall.org', 'Matsumoto' : 'matz@ruby-lang.org', 'Spammer' : 'spammer@hotmail.com' }print "Swaroop's address is %s" % ab['Swaroop']# Adding a key/value pairab['Guido'] = 'guido@python.org'# Deleting a key/value pairdel ab['Spammer']print '\nThere are %d contacts in the address-book\n' % len(ab)for name, address in ab.items(): print 'Contact %s at %s' % (name, address)if 'Guido' in ab: # OR ab.has_key('Guido') print "\nGuido's address is %s" % ab['Guido']
4、序列
列表、元組和字串都是序列。序列的兩個主要特點是索引操作符和切片操作符。
shoplist = ['apple', 'mango', 'carrot', 'banana']# Indexing or 'Subscription' operationprint 'Item 0 is', shoplist[0]print 'Item 1 is', shoplist[1]print 'Item -1 is', shoplist[-1]print 'Item -2 is', shoplist[-2]# Slicing on a listprint 'Item 1 to 3 is', shoplist[1:3]print 'Item 2 to end is', shoplist[2:]print 'Item 1 to -1 is', shoplist[1:-1]print 'Item start to end is', shoplist[:]# Slicing on a stringname = 'swaroop'print 'characters 1 to 3 is', name[1:3]print 'characters 2 to end is', name[2:]print 'characters 1 to -1 is', name[1:-1]print 'characters start to end is', name[:]
5、參考
當你建立一個對象並給它賦一個變數的時候,這個變數僅僅參考那個對象,而不是表示這個對象本身!也就是說,變數名指向你電腦中儲存那個對象的記憶體。這被稱作名稱到對象的綁定。
print 'Simple Assignment'shoplist = ['apple', 'mango', 'carrot', 'banana']mylist = shoplist # mylist is just another name pointing to the same object!del shoplist[0]print 'shoplist is', shoplistprint 'mylist is', mylist# notice that both shoplist and mylist both print the same list without# the 'apple' confirming that they point to the same objectprint 'Copy by making a full slice'mylist = shoplist[:] # make a copy by doing a full slicedel mylist[0] # remove first itemprint 'shoplist is', shoplistprint 'mylist is', mylist# notice that now the two lists are different
6、字串
name = 'Swaroop' # This is a string objectif name.startswith('Swa'): print 'Yes, the string starts with "Swa"'if 'a' in name: print 'Yes, it contains the string "a"'if name.find('war') != -1: print 'Yes, it contains the string "war"'delimiter = '_*_'mylist = ['Brazil', 'Russia', 'India', 'China']print delimiter.join(mylist) //用delimiter來串連mylist的字元
六、物件導向的編程
1、self
Python中的self等價於C++中的self指標和Java、C#中的this參考
2、建立類
class Person: pass # An empty blockp = Person()print p
3、對象的方法
class Person: def sayHi(self): print 'Hello, how are you?'p = Person()p.sayHi()
4、初始化
class Person: def __init__(self, name): self.name = name def sayHi(self): print 'Hello, my name is', self.namep = Person('Swaroop')p.sayHi()
5、類與對象的方法
類的變數 由一個類的所有對象(執行個體)共用使用。只有一個類變數的拷貝,所以當某個對象對類的變數做了改動的時候,這個改動會反映到所有其他的執行個體上。
對象的變數 由類的每個對象/執行個體擁有。因此每個對象有自己對這個域的一份拷貝,即它們不是共用的,在同一個類的不同執行個體中,雖然對象的變數有相同的名稱,但是是互不相關的。
class Person: '''Represents a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' self.name = name print '(Initializing %s)' % self.name # When this person is created, he/she # adds to the population Person.population += 1
population屬於Person類,因此是一個類的變數。name變數屬於對象(它使用self賦值)因此是對象的變數。
6、繼承
class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = nameclass Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary
七、輸入輸出
1、檔案
f = file('poem.txt', 'w') # open for 'w'ritingf.write(poem) # write text to filef.close() # close the filef = file('poem.txt')# if no mode is specified, 'r'ead mode is assumed by defaultwhile True: line = f.readline() if len(line) == 0: # Zero length indicates EOF break print line, # Notice comma to avoid automatic newline added by Pythonf.close() # close the file
2、儲存空間
持久性
import cPickle as p#import pickle as pshoplistfile = 'shoplist.data'# the name of the file where we will store the objectshoplist = ['apple', 'mango', 'carrot']# Write to the filef = file(shoplistfile, 'w')p.dump(shoplist, f) # dump the object to a filef.close()del shoplist # remove the shoplist# Read back from the storagef = file(shoplistfile)storedlist = p.load(f)print storedlist
3、控制台輸入
輸入字串 nID = raw_input("Input your id plz")
輸入整數 nAge = int(raw_input("input your age plz:\n"))
輸入浮點型 fWeight = float(raw_input("input your weight\n"))
輸入16進位資料 nHex = int(raw_input('input hex value(like 0x20):\n'),16)
輸入8進位資料 nOct = int(raw_input('input oct value(like 020):\n'),8)
八、異常
1、try..except
import systry: s = raw_input('Enter something --> ')except EOFError: print '\nWhy did you do an EOF on me?' sys.exit() # exit the programexcept: print '\nSome error/exception occurred.' # here, we are not exiting the programprint 'Done'
2、引發異常
使用raise語句引發異常。你還得指明錯誤/異常的名稱和伴隨異常 觸發的 異常對象。你可以引發的錯誤或異常應該分別是一個Error或Exception類的直接或間接匯出類。
class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleastraise ShortInputException(len(s), 3)
3、try..finnally
import timetry: f = file('poem.txt') while True: # our usual file-reading idiom line = f.readline() if len(line) == 0: break time.sleep(2) print line,finally: f.close() print 'Cleaning up...closed the file'
九、Python標準庫
1、sys庫
sys模組包含系統對應的功能。sys.argv列表,它包含命令列參數。
2、os庫
os.name字串指示你正在使用的平台。比如對於Windows,它是'nt',而對於Linux/Unix使用者,它是'posix'。
os.getcwd()函數得到當前工作目錄,即當前Python指令碼工作的目錄路徑。
os.getenv()和os.putenv()函數分別用來讀取和設定環境變數。
os.listdir()返回指定目錄下的所有檔案和目錄名。
os.remove()函數用來刪除一個檔案。
os.system()函數用來運行shell命令。
os.linesep字串給出當前平台使用的行終止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
os.path.split()函數返回一個路徑的目錄名和檔案名稱。
>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
os.path.isfile()和os.path.isdir()函數分別檢驗給出的路徑是一個檔案還是目錄。類似地,os.path.existe()函數用來檢驗給出的路徑是否真地存在。
希望本文所述對大家的Python程式設計有所協助。