這篇文章主要介紹python語(yǔ)言基礎(chǔ)知識(shí)有哪些,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
Python 是 90 年代初由 Guido Van Rossum 創(chuàng)立的。它是當(dāng)前最流行的程序語(yǔ)言之一。它那純凈的語(yǔ)法令我一見(jiàn)傾心,它簡(jiǎn)直就是可以運(yùn)行的偽碼。
請(qǐng)注意:本文以 Python 2.7 為基準(zhǔn),但也應(yīng)該適用于所有 2.X 版本。還要繼續(xù)學(xué)習(xí)最新的 Python 3 哦!
# Single line comments start with a hash. # 單行注釋由一個(gè)井號(hào)開(kāi)頭。 """ Multiline strings can be written using three "'s, and are often used as comments 三個(gè)雙引號(hào)(或單引號(hào))之間可以寫(xiě)多行字符串, 通常用來(lái)寫(xiě)注釋。 """ #################################################### ## 1. Primitive Datatypes and Operators ## 1. 基本數(shù)據(jù)類(lèi)型和操作符 #################################################### # You have numbers # 數(shù)字就是數(shù)字 3 #=> 3 # Math is what you would expect # 四則運(yùn)算也是你所期望的那樣 1 + 1 #=> 2 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 # Division is a bit tricky. It is integer division and floors the results # automatically. # 除法有一點(diǎn)棘手。 # 對(duì)于整數(shù)除法來(lái)說(shuō),計(jì)算結(jié)果會(huì)自動(dòng)取整。 5 / 2 #=> 2 # To fix division we need to learn about floats. # 為了修正除法的問(wèn)題,我們需要先學(xué)習(xí)浮點(diǎn)數(shù)。 2.0 # This is a float 2.0 # 這是一個(gè)浮點(diǎn)數(shù) 11.0 / 4.0 #=> 2.75 ahhh...much better 11.0 / 4.0 #=> 2.75 啊……這樣就好多了 # Enforce precedence with parentheses # 使用小括號(hào)來(lái)強(qiáng)制計(jì)算的優(yōu)先順序 (1 + 3) * 2 #=> 8 # Boolean values are primitives # 布爾值也是基本數(shù)據(jù)類(lèi)型 True False # negate with not # 使用 not 來(lái)取反 not True #=> False not False #=> True # Equality is == # 等式判斷用 == 1 == 1 #=> True 2 == 1 #=> False # Inequality is != # 不等式判斷是用 != 1 != 1 #=> False 2 != 1 #=> True # More comparisons # 還有更多的比較運(yùn)算 1 < 10 #=> True 1 > 10 #=> False 2 <= 2 #=> True 2 >= 2 #=> True # Comparisons can be chained! # 居然可以把比較運(yùn)算串連起來(lái)! 1 < 2 < 3 #=> True 2 < 3 < 2 #=> False # Strings are created with " or ' # 使用 " 或 ' 來(lái)創(chuàng)建字符串 "This is a string." 'This is also a string.' # Strings can be added too! # 字符串也可以相加! "Hello " + "world!" #=> "Hello world!" # A string can be treated like a list of characters # 一個(gè)字符串可以視為一個(gè)字符的列表 # (譯注:后面會(huì)講到“列表”。) "This is a string"[0] #=> 'T' # % can be used to format strings, like this: # % 可以用來(lái)格式化字符串,就像這樣: "%s can be %s" % ("strings", "interpolated") # A newer way to format strings is the format method. # This method is the preferred way # 后來(lái)又有一種格式化字符串的新方法:format 方法。 # 我們推薦使用這個(gè)方法。 "{0} can be {1}".format("strings", "formatted") # You can use keywords if you don't want to count. # 如果你不喜歡數(shù)數(shù)的話(huà),可以使用關(guān)鍵字(變量)。 "{name} wants to eat {food}".format(name="Bob", food="lasagna") # None is an object # None 是一個(gè)對(duì)象 None #=> None # Don't use the equality `==` symbol to compare objects to None # Use `is` instead # 不要使用相等符號(hào) `==` 來(lái)把對(duì)象和 None 進(jìn)行比較, # 而要用 `is`。 "etc" is None #=> False None is None #=> True # The 'is' operator tests for object identity. This isn't # very useful when dealing with primitive values, but is # very useful when dealing with objects. # 這個(gè) `is` 操作符用于比較兩個(gè)對(duì)象的標(biāo)識(shí)。 # (譯注:對(duì)象一旦建立,其標(biāo)識(shí)就不會(huì)改變,可以認(rèn)為它就是對(duì)象的內(nèi)存地址。) # 在處理基本數(shù)據(jù)類(lèi)型時(shí)基本用不上, # 但它在處理對(duì)象時(shí)很有用。 # None, 0, and empty strings/lists all evaluate to False. # All other values are True # None、0 以及空字符串和空列表都等于 False, # 除此以外的所有值都等于 True。 0 == False #=> True "" == False #=> True #################################################### ## 2. Variables and Collections ## 2. 變量和集合 #################################################### # Printing is pretty easy # 打印輸出很簡(jiǎn)單 print "I'm Python. Nice to meet you!" # No need to declare variables before assigning to them. # 在賦值給變量之前不需要聲明 some_var = 5 # Convention is to use lower_case_with_underscores # 變量名的約定是使用下劃線(xiàn)分隔的小寫(xiě)單詞 some_var #=> 5 # Accessing a previously unassigned variable is an exception. # See Control Flow to learn more about exception handling. # 訪(fǎng)問(wèn)一個(gè)未賦值的變量會(huì)產(chǎn)生一個(gè)異常。 # 進(jìn)一步了解異常處理,可參見(jiàn)下一節(jié)《控制流》。 some_other_var # Raises a name error # 會(huì)拋出一個(gè)名稱(chēng)錯(cuò)誤 # if can be used as an expression # if 可以作為表達(dá)式來(lái)使用 "yahoo!" if 3 > 2 else 2 #=> "yahoo!" # Lists store sequences # 列表用于存儲(chǔ)序列 li = [] # You can start with a prefilled list # 我們先嘗試一個(gè)預(yù)先填充好的列表 other_li = [4, 5, 6] # Add stuff to the end of a list with append # 使用 append 方法把元素添加到列表的尾部 li.append(1) #li is now [1] #li 現(xiàn)在是 [1] li.append(2) #li is now [1, 2] #li 現(xiàn)在是 [1, 2] li.append(4) #li is now [1, 2, 4] #li 現(xiàn)在是 [1, 2, 4] li.append(3) #li is now [1, 2, 4, 3] #li 現(xiàn)在是 [1, 2, 4, 3] # Remove from the end with pop # 使用 pop 來(lái)移除最后一個(gè)元素 li.pop() #=> 3 and li is now [1, 2, 4] #=> 3,然后 li 現(xiàn)在是 [1, 2, 4] # Let's put it back # 我們?cè)侔阉呕厝?li.append(3) # li is now [1, 2, 4, 3] again. # li 現(xiàn)在又是 [1, 2, 4, 3] 了 # Access a list like you would any array # 像訪(fǎng)問(wèn)其它語(yǔ)言的數(shù)組那樣訪(fǎng)問(wèn)列表 li[0] #=> 1 # Look at the last element # 查詢(xún)最后一個(gè)元素 li[-1] #=> 3 # Looking out of bounds is an IndexError # 越界查詢(xún)會(huì)產(chǎn)生一個(gè)索引錯(cuò)誤 li[4] # Raises an IndexError # 拋出一個(gè)索引錯(cuò)誤 # You can look at ranges with slice syntax. # (It's a closed/open range for you mathy types.) # 你可以使用切片語(yǔ)法來(lái)查詢(xún)列表的一個(gè)范圍。 # (這個(gè)范圍相當(dāng)于數(shù)學(xué)中的左閉右開(kāi)區(qū)間。) li[1:3] #=> [2, 4] # Omit the beginning # 省略開(kāi)頭 li[2:] #=> [4, 3] # Omit the end # 省略結(jié)尾 li[:3] #=> [1, 2, 4] # Remove arbitrary elements from a list with del # 使用 del 來(lái)刪除列表中的任意元素 del li[2] # li is now [1, 2, 3] # li 現(xiàn)在是 [1, 2, 3] # You can add lists # 可以把列表相加 li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone #=> [1, 2, 3, 4, 5, 6] - 請(qǐng)留意 li 和 other_li 并不會(huì)被修改 # Concatenate lists with extend # 使用 extend 來(lái)合并列表 li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # 現(xiàn)在 li 是 [1, 2, 3, 4, 5, 6] # Check for existence in a list with in # 用 in 來(lái)檢查是否存在于某個(gè)列表中 1 in li #=> True # Examine the length with len # 用 len 來(lái)檢測(cè)列表的長(zhǎng)度 len(li) #=> 6 # Tuples are like lists but are immutable. # 元組很像列表,但它是“不可變”的。 tup = (1, 2, 3) tup[0] #=> 1 tup[0] = 3 # Raises a TypeError # 拋出一個(gè)類(lèi)型錯(cuò)誤 # You can do all those list thingies on tuples too # 操作列表的方式通常也能用在元組身上 len(tup) #=> 3 tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup[:2] #=> (1, 2) 2 in tup #=> True # You can unpack tuples (or lists) into variables # 你可以把元組(或列表)中的元素解包賦值給多個(gè)變量 a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 # 現(xiàn)在 a 是 1,b 是 2,c 是 3 # Tuples are created by default if you leave out the parentheses # 如果你省去了小括號(hào),那么元組會(huì)被自動(dòng)創(chuàng)建 d, e, f = 4, 5, 6 # Now look how easy it is to swap two values # 再來(lái)看看交換兩個(gè)值是多么簡(jiǎn)單。 e, d = d, e # d is now 5 and e is now 4 # 現(xiàn)在 d 是 5 而 e 是 4 # Dictionaries store mappings # 字典用于存儲(chǔ)映射關(guān)系 empty_dict = {} # Here is a prefilled dictionary # 這是一個(gè)預(yù)先填充的字典 filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] # 使用 [] 來(lái)查詢(xún)鍵值 filled_dict["one"] #=> 1 # Get all keys as a list # 將字典的所有鍵名獲取為一個(gè)列表 filled_dict.keys() #=> ["three", "two", "one"] # Note - Dictionary key ordering is not guaranteed. # Your results might not match this exactly. # 請(qǐng)注意:無(wú)法保證字典鍵名的順序如何排列。 # 你得到的結(jié)果可能跟上面的示例不一致。 # Get all values as a list # 將字典的所有鍵值獲取為一個(gè)列表 filled_dict.values() #=> [3, 2, 1] # Note - Same as above regarding key ordering. # 請(qǐng)注意:順序的問(wèn)題和上面一樣。 # Check for existence of keys in a dictionary with in # 使用 in 來(lái)檢查一個(gè)字典是否包含某個(gè)鍵名 "one" in filled_dict #=> True 1 in filled_dict #=> False # Looking up a non-existing key is a KeyError # 查詢(xún)一個(gè)不存在的鍵名會(huì)產(chǎn)生一個(gè)鍵名錯(cuò)誤 filled_dict["four"] # KeyError # 鍵名錯(cuò)誤 # Use get method to avoid the KeyError # 所以要使用 get 方法來(lái)避免鍵名錯(cuò)誤 filled_dict.get("one") #=> 1 filled_dict.get("four") #=> None # The get method supports a default argument when the value is missing # get 方法支持傳入一個(gè)默認(rèn)值參數(shù),將在取不到值時(shí)返回。 filled_dict.get("one", 4) #=> 1 filled_dict.get("four", 4) #=> 4 # Setdefault method is a safe way to add new key-value pair into dictionary # Setdefault 方法可以安全地把新的名值對(duì)添加到字典里 filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 #filled_dict["five"] 被設(shè)置為 5 filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 #filled_dict["five"] 仍然為 5 # Sets store ... well sets # set 用于保存集合 empty_set = set() # Initialize a set with a bunch of values # 使用一堆值來(lái)初始化一個(gè)集合 some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) # some_set 現(xiàn)在是 set([1, 2, 3, 4]) # Since Python 2.7, {} can be used to declare a set # 從 Python 2.7 開(kāi)始,{} 可以用來(lái)聲明一個(gè)集合 filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # (譯注:集合是種無(wú)序不重復(fù)的元素集,因此重復(fù)的 2 被濾除了。) # (譯注:{} 不會(huì)創(chuàng)建一個(gè)空集合,只會(huì)創(chuàng)建一個(gè)空字典。) # Add more items to a set # 把更多的元素添加進(jìn)一個(gè)集合 filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # filled_set 現(xiàn)在是 {1, 2, 3, 4, 5} # Do set intersection with & # 使用 & 來(lái)獲取交集 other_set = {3, 4, 5, 6} filled_set & other_set #=> {3, 4, 5} # Do set union with | # 使用 | 來(lái)獲取并集 filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # Do set difference with - # 使用 - 來(lái)獲取補(bǔ)集 {1,2,3,4} - {2,3,5} #=> {1, 4} # Check for existence in a set with in # 使用 in 來(lái)檢查是否存在于某個(gè)集合中 2 in filled_set #=> True 10 in filled_set #=> False #################################################### ## 3. Control Flow ## 3. 控制流 #################################################### # Let's just make a variable # 我們先創(chuàng)建一個(gè)變量 some_var = 5 # Here is an if statement. Indentation is significant in python! # prints "some_var is smaller than 10" # 這里有一個(gè)條件語(yǔ)句。縮進(jìn)在 Python 中可是很重要的哦! # 程序會(huì)打印出 "some_var is smaller than 10" # (譯注:意為“some_var 比 10 小”。) if some_var > 10: print "some_var is totally bigger than 10." # (譯注:意為“some_var 完全比 10 大”。) elif some_var < 10: # This elif clause is optional. # 這里的 elif 子句是可選的 print "some_var is smaller than 10." # (譯注:意為“some_var 比 10 小”。) else: # This is optional too. # 這一句也是可選的 print "some_var is indeed 10." # (譯注:意為“some_var 就是 10”。) """ For loops iterate over lists for 循環(huán)可以遍歷列表 prints: 如果要打印出: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: # You can use % to interpolate formatted strings # 別忘了你可以使用 % 來(lái)格式化字符串 print "%s is a mammal" % animal # (譯注:意為“%s 是哺乳動(dòng)物”。) """ `range(number)` returns a list of numbers from zero to the given number `range(數(shù)字)` 會(huì)返回一個(gè)數(shù)字列表, 這個(gè)列表將包含從零到給定的數(shù)字。 prints: 如果要打印出: 0 1 2 3 """ for i in range(4): print i """ While loops go until a condition is no longer met. while 循環(huán)會(huì)一直繼續(xù),直到條件不再滿(mǎn)足。 prints: 如果要打印出: 0 1 2 3 """ x = 0 while x < 4: print x x += 1 # Shorthand for x = x + 1 # 這是 x = x + 1 的簡(jiǎn)寫(xiě)方式 # Handle exceptions with a try/except block # 使用 try/except 代碼塊來(lái)處理異常 # Works on Python 2.6 and up: # 適用于 Python 2.6 及以上版本: try: # Use raise to raise an error # 使用 raise 來(lái)拋出一個(gè)錯(cuò)誤 raise IndexError("This is an index error") # 拋出一個(gè)索引錯(cuò)誤:“這是一個(gè)索引錯(cuò)誤”。 except IndexError as e: pass # Pass is just a no-op. Usually you would do recovery here. # pass 只是一個(gè)空操作。通常你應(yīng)該在這里做一些恢復(fù)工作。 #################################################### ## 4. Functions ## 4. 函數(shù) #################################################### # Use def to create new functions # 使用 def 來(lái)創(chuàng)建新函數(shù) def add(x, y): print "x is %s and y is %s" % (x, y) # (譯注:意為“x 是 %s 而且 y 是 %s”。) return x + y # Return values with a return statement # 使用 return 語(yǔ)句來(lái)返回值 # Calling functions with parameters # 調(diào)用函數(shù)并傳入?yún)?shù) add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11 # (譯注:意為“x 是 5 而且 y 是 6”,并返回 11) # Another way to call functions is with keyword arguments # 調(diào)用函數(shù)的另一種方式是傳入關(guān)鍵字參數(shù) add(y=6, x=5) # Keyword arguments can arrive in any order. # 關(guān)鍵字參數(shù)可以以任意順序傳入 # You can define functions that take a variable number of # positional arguments # 你可以定義一個(gè)函數(shù),并讓它接受可變數(shù)量的定位參數(shù)。 def varargs(*args): return args varargs(1, 2, 3) #=> (1,2,3) # You can define functions that take a variable number of # keyword arguments, as well # 你也可以定義一個(gè)函數(shù),并讓它接受可變數(shù)量的關(guān)鍵字參數(shù)。 def keyword_args(**kwargs): return kwargs # Let's call it to see what happens # 我們?cè)囍{(diào)用它,看看會(huì)發(fā)生什么: keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} # You can do both at once, if you like # 你還可以同時(shí)使用這兩類(lèi)參數(shù),只要你愿意: def all_the_args(*args, **kwargs): print args print kwargs """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) {"a": 3, "b": 4} """ # When calling functions, you can do the opposite of varargs/kwargs! # Use * to expand tuples and use ** to expand kwargs. # 在調(diào)用函數(shù)時(shí),定位參數(shù)和關(guān)鍵字參數(shù)還可以反過(guò)來(lái)用。 # 使用 * 來(lái)展開(kāi)元組,使用 ** 來(lái)展開(kāi)關(guān)鍵字參數(shù)。 args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) # equivalent to foo(1, 2, 3, 4) # 相當(dāng)于 all_the_args(1, 2, 3, 4) all_the_args(**kwargs) # equivalent to foo(a=3, b=4) # 相當(dāng)于 all_the_args(a=3, b=4) all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # 相當(dāng)于 all_the_args(1, 2, 3, 4, a=3, b=4) # Python has first class functions # 函數(shù)在 Python 中是一等公民 def create_adder(x): def adder(y): return x + y return adder add_10 = create_adder(10) add_10(3) #=> 13 # There are also anonymous functions # 還有匿名函數(shù) (lambda x: x > 2)(3) #=> True # There are built-in higher order functions # 還有一些內(nèi)建的高階函數(shù) map(add_10, [1,2,3]) #=> [11, 12, 13] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # We can use list comprehensions for nice maps and filters # 我們可以使用列表推導(dǎo)式來(lái)模擬 map 和 filter [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] #################################################### ## 5. Classes ## 5. 類(lèi) #################################################### # We subclass from object to get a class. # 我們可以從對(duì)象中繼承,來(lái)得到一個(gè)類(lèi)。 class Human(object): # A class attribute. It is shared by all instances of this class # 下面是一個(gè)類(lèi)屬性。它將被這個(gè)類(lèi)的所有實(shí)例共享。 species = "H. sapiens" # Basic initializer # 基本的初始化函數(shù)(構(gòu)造函數(shù)) def __init__(self, name): # Assign the argument to the instance's name attribute # 把參數(shù)賦值為實(shí)例的 name 屬性 self.name = name # An instance method. All methods take self as the first argument # 下面是一個(gè)實(shí)例方法。所有方法都以 self 作為第一個(gè)參數(shù)。 def say(self, msg): return "%s: %s" % (self.name, msg) # A class method is shared among all instances # They are called with the calling class as the first argument # 類(lèi)方法會(huì)被所有實(shí)例共享。 # 類(lèi)方法在調(diào)用時(shí),會(huì)將類(lèi)本身作為第一個(gè)函數(shù)傳入。 @classmethod def get_species(cls): return cls.species # A static method is called without a class or instance reference # 靜態(tài)方法在調(diào)用時(shí),不會(huì)傳入類(lèi)或?qū)嵗囊谩? @staticmethod def grunt(): return "*grunt*" # Instantiate a class # 實(shí)例化一個(gè)類(lèi) i = Human(name="Ian") print i.say("hi") # prints out "Ian: hi" # 打印出 "Ian: hi" j = Human("Joel") print j.say("hello") # prints out "Joel: hello" # 打印出 "Joel: hello" # Call our class method # 調(diào)用我們的類(lèi)方法 i.get_species() #=> "H. sapiens" # Change the shared attribute # 修改共享屬性 Human.species = "H. neanderthalensis" i.get_species() #=> "H. neanderthalensis" j.get_species() #=> "H. neanderthalensis" # Call the static method # 調(diào)用靜態(tài)方法 Human.grunt() #=> "*grunt*" #################################################### ## 6. Modules ## 6. 模塊 #################################################### # You can import modules # 你可以導(dǎo)入模塊 import math print math.sqrt(16) #=> 4 # You can get specific functions from a module # 也可以從一個(gè)模塊中獲取指定的函數(shù) from math import ceil, floor print ceil(3.7) #=> 4.0 print floor(3.7) #=> 3.0 # You can import all functions from a module. # Warning: this is not recommended # 你可以從一個(gè)模塊中導(dǎo)入所有函數(shù) # 警告:不建議使用這種方式 from math import * # You can shorten module names # 你可以縮短模塊的名稱(chēng) import math as m math.sqrt(16) == m.sqrt(16) #=> True # Python modules are just ordinary python files. You # can write your own, and import them. The name of the # module is the same as the name of the file. # Python 模塊就是普通的 Python 文件。 # 你可以編寫(xiě)你自己的模塊,然后導(dǎo)入它們。 # 模塊的名稱(chēng)與文件名相同。 # You can find out which functions and attributes # defines a module. # 你可以查出一個(gè)模塊里有哪些函數(shù)和屬性 import math dir(math)
以上是“python語(yǔ)言基礎(chǔ)知識(shí)有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
當(dāng)前名稱(chēng):python語(yǔ)言基礎(chǔ)知識(shí)有哪些-創(chuàng)新互聯(lián)
URL分享:http://jinyejixie.com/article28/coejjp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、標(biāo)簽優(yōu)化、網(wǎng)頁(yè)設(shè)計(jì)公司、軟件開(kāi)發(fā)、微信公眾號(hào)、建站公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容