Python 是 90 年代初由 Guido Van Rossum 創立的。它是當前最流行的程序語言之一。它那純凈的語法令我一見傾心,它簡直就是可以運行的偽碼。
請注意:本文以 Python 2.7 為基準,但也應該適用于所有 2.X 版本。還要繼續學習最新的 Python 3 哦!
# Single line comments start with a hash.# 單行注釋由一個井號開頭。""" Multiline strings can be written using three "'s, and are often used as comments 三個雙引號(或單引號)之間可以寫多行字符串, 通常用來寫注釋。""" ###################################################### 1. Primitive Datatypes and Operators## 1. 基本數據類型和操作符#################################################### # You have numbers# 數字就是數字3 #=> 3 # Math is what you would expect# 四則運算也是你所期望的那樣1 + 1 #=> 28 - 1 #=> 710 * 2 #=> 2035 / 5 #=> 7 # Division is a bit tricky. It is integer division and floors the results# automatically.# 除法有一點棘手。# 對于整數除法來說,計算結果會自動取整。5 / 2 #=> 2 # To fix division we need to learn about floats.# 為了修正除法的問題,我們需要先學習浮點數。2.0 # This is a float2.0 # 這是一個浮點數11.0 / 4.0 #=> 2.75 ahhh...much better11.0 / 4.0 #=> 2.75 啊……這樣就好多了 # Enforce precedence with parentheses# 使用小括號來強制計算的優先順序(1 + 3) * 2 #=> 8 # Boolean values are primitives# 布爾值也是基本數據類型TrueFalse # negate with not# 使用 not 來取反not True #=> Falsenot False #=> True # Equality is ==# 等式判斷用 ==1 == 1 #=> True2 == 1 #=> False # Inequality is !=# 不等式判斷是用 !=1 != 1 #=> False2 != 1 #=> True # More comparisons# 還有更多的比較運算1 < 10 #=> True1 > 10 #=> False2 <= 2 #=> True2 >= 2 #=> True # Comparisons can be chained!# 居然可以把比較運算串連起來!1 < 2 < 3 #=> True2 < 3 < 2 #=> False # Strings are created with " or '# 使用 " 或 ' 來創建字符串"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# 一個字符串可以視為一個字符的列表# (譯注:后面會講到“列表”。)"This is a string"[0] #=> 'T' # % can be used to format strings, like this:# % 可以用來格式化字符串,就像這樣:"%s can be %s" % ("strings", "interpolated") # A newer way to format strings is the format method.# This method is the preferred way# 后來又有一種格式化字符串的新方法:format 方法。# 我們推薦使用這個方法。"{0} can be {1}".format("strings", "formatted") # You can use keywords if you don't want to count.# 如果你不喜歡數數的話,可以使用關鍵字(變量)。"{name} wants to eat {food}".format(name="Bob", food="lasagna") # None is an object# None 是一個對象None #=> None # Don't use the equality `==` symbol to compare objects to None# Use `is` instead# 不要使用相等符號 `==` 來把對象和 None 進行比較,# 而要用 `is`。"etc" is None #=> FalseNone 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.# 這個 `is` 操作符用于比較兩個對象的標識。# (譯注:對象一旦建立,其標識就不會改變,可以認為它就是對象的內存地址。)# 在處理基本數據類型時基本用不上,# 但它在處理對象時很有用。 # 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# 打印輸出很簡單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 # 變量名的約定是使用下劃線分隔的小寫單詞some_var #=> 5 # Accessing a previously unassigned variable is an exception.# See Control Flow to learn more about exception handling.# 訪問一個未賦值的變量會產生一個異常。# 進一步了解異常處理,可參見下一節《控制流》。some_other_var # Raises a name error # 會拋出一個名稱錯誤 # if can be used as an expression# if 可以作為表達式來使用"yahoo!" if 3 > 2 else 2 #=> "yahoo!" # Lists store sequences# 列表用于存儲序列li = []# You can start with a prefilled list# 我們先嘗試一個預先填充好的列表other_li = [4, 5, 6] # Add stuff to the end of a list with append# 使用 append 方法把元素添加到列表的尾部li.append(1) #li is now [1] #li 現在是 [1]li.append(2) #li is now [1, 2] #li 現在是 [1, 2]li.append(4) #li is now [1, 2, 4] #li 現在是 [1, 2, 4]li.append(3) #li is now [1, 2, 4, 3] #li 現在是 [1, 2, 4, 3]# Remove from the end with pop# 使用 pop 來移除最后一個元素li.pop() #=> 3 and li is now [1, 2, 4] #=> 3,然后 li 現在是 [1, 2, 4]# Let's put it back# 我們再把它放回去li.append(3) # li is now [1, 2, 4, 3] again. # li 現在又是 [1, 2, 4, 3] 了 # Access a list like you would any array# 像訪問其它語言的數組那樣訪問列表li[0] #=> 1# Look at the last element# 查詢最后一個元素li[-1] #=> 3 # Looking out of bounds is an IndexError# 越界查詢會產生一個索引錯誤li[4] # Raises an IndexError # 拋出一個索引錯誤 # You can look at ranges with slice syntax.# (It's a closed/open range for you mathy types.)# 你可以使用切片語法來查詢列表的一個范圍。# (這個范圍相當于數學中的左閉右開區間。)li[1:3] #=> [2, 4]# Omit the beginning# 省略開頭li[2:] #=> [4, 3]# Omit the end# 省略結尾li[:3] #=> [1, 2, 4] # Remove arbitrary elements from a list with del# 使用 del 來刪除列表中的任意元素del li[2] # li is now [1, 2, 3] # li 現在是 [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] - 請留意 li 和 other_li 并不會被修改 # Concatenate lists with extend# 使用 extend 來合并列表li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # 現在 li 是 [1, 2, 3, 4, 5, 6] # Check for existence in a list with in# 用 in 來檢查是否存在于某個列表中1 in li #=> True # Examine the length with len# 用 len 來檢測列表的長度len(li) #=> 6 # Tuples are like lists but are immutable.# 元組很像列表,但它是“不可變”的。tup = (1, 2, 3)tup[0] #=> 1tup[0] = 3 # Raises a TypeError # 拋出一個類型錯誤 # You can do all those list thingies on tuples too# 操作列表的方式通常也能用在元組身上len(tup) #=> 3tup + (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# 你可以把元組(或列表)中的元素解包賦值給多個變量a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 # 現在 a 是 1,b 是 2,c 是 3# Tuples are created by default if you leave out the parentheses# 如果你省去了小括號,那么元組會被自動創建d, e, f = 4, 5, 6# Now look how easy it is to swap two values# 再來看看交換兩個值是多么簡單。e, d = d, e # d is now 5 and e is now 4 # 現在 d 是 5 而 e 是 4 # Dictionaries store mappings# 字典用于存儲映射關系empty_dict = {}# Here is a prefilled dictionary# 這是一個預先填充的字典filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with []# 使用 [] 來查詢鍵值filled_dict["one"] #=> 1 # Get all keys as a list# 將字典的所有鍵名獲取為一個列表filled_dict.keys() #=> ["three", "two", "one"]# Note - Dictionary key ordering is not guaranteed.# Your results might not match this exactly.# 請注意:無法保證字典鍵名的順序如何排列。# 你得到的結果可能跟上面的示例不一致。 # Get all values as a list# 將字典的所有鍵值獲取為一個列表filled_dict.values() #=> [3, 2, 1]# Note - Same as above regarding key ordering.# 請注意:順序的問題和上面一樣。 # Check for existence of keys in a dictionary with in# 使用 in 來檢查一個字典是否包含某個鍵名"one" in filled_dict #=> True1 in filled_dict #=> False # Looking up a non-existing key is a KeyError# 查詢一個不存在的鍵名會產生一個鍵名錯誤filled_dict["four"] # KeyError # 鍵名錯誤 # Use get method to avoid the KeyError# 所以要使用 get 方法來避免鍵名錯誤filled_dict.get("one") #=> 1filled_dict.get("four") #=> None# The get method supports a default argument when the value is missing# get 方法支持傳入一個默認值參數,將在取不到值時返回。filled_dict.get("one", 4) #=> 1filled_dict.get("four", 4) #=> 4 # Setdefault method is a safe way to add new key-value pair into dictionary# Setdefault 方法可以安全地把新的名值對添加到字典里filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 #filled_dict["five"] 被設置為 5filled_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# 使用一堆值來初始化一個集合some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4]) # some_set 現在是 set([1, 2, 3, 4]) # Since Python 2.7, {} can be used to declare a set# 從 Python 2.7 開始,{} 可以用來聲明一個集合filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # (譯注:集合是種無序不重復的元素集,因此重復的 2 被濾除了。) # (譯注:{} 不會創建一個空集合,只會創建一個空字典。) # Add more items to a set# 把更多的元素添加進一個集合filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # filled_set 現在是 {1, 2, 3, 4, 5} # Do set intersection with &# 使用 & 來獲取交集other_set = {3, 4, 5, 6}filled_set & other_set #=> {3, 4, 5} # Do set union with |# 使用 | 來獲取并集filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # Do set difference with -# 使用 - 來獲取補集{1,2,3,4} - {2,3,5} #=> {1, 4} # Check for existence in a set with in# 使用 in 來檢查是否存在于某個集合中2 in filled_set #=> True10 in filled_set #=> False ###################################################### 3. Control Flow## 3. 控制流#################################################### # Let's just make a variable# 我們先創建一個變量some_var = 5 # Here is an if statement. Indentation is significant in python!# prints "some_var is smaller than 10"# 這里有一個條件語句。縮進在 Python 中可是很重要的哦!# 程序會打印出 "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 listsfor 循環可以遍歷列表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 # 別忘了你可以使用 % 來格式化字符串 print "%s is a mammal" % animal # (譯注:意為“%s 是哺乳動物”。) """`range(number)` returns a list of numbers from zero to the given number`range(數字)` 會返回一個數字列表,這個列表將包含從零到給定的數字。prints:如果要打印出: 0 1 2 3"""for i in range(4): print i """While loops go until a condition is no longer met.while 循環會一直繼續,直到條件不再滿足。prints:如果要打印出: 0 1 2 3"""x = 0while x < 4: print x x += 1 # Shorthand for x = x + 1 # 這是 x = x + 1 的簡寫方式 # Handle exceptions with a try/except block# 使用 try/except 代碼塊來處理異常 # Works on Python 2.6 and up:# 適用于 Python 2.6 及以上版本:try: # Use raise to raise an error # 使用 raise 來拋出一個錯誤 raise IndexError("This is an index error") # 拋出一個索引錯誤:“這是一個索引錯誤”。except IndexError as e: pass # Pass is just a no-op. Usually you would do recovery here. # pass 只是一個空操作。通常你應該在這里做一些恢復工作。 ###################################################### 4. Functions## 4. 函數#################################################### # Use def to create new functions# 使用 def 來創建新函數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 語句來返回值 # Calling functions with parameters# 調用函數并傳入參數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# 調用函數的另一種方式是傳入關鍵字參數add(y=6, x=5) # Keyword arguments can arrive in any order. # 關鍵字參數可以以任意順序傳入 # You can define functions that take a variable number of# positional arguments# 你可以定義一個函數,并讓它接受可變數量的定位參數。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# 你也可以定義一個函數,并讓它接受可變數量的關鍵字參數。def keyword_args(**kwargs): return kwargs # Let's call it to see what happens# 我們試著調用它,看看會發生什么:keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} # You can do both at once, if you like# 你還可以同時使用這兩類參數,只要你愿意: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.# 在調用函數時,定位參數和關鍵字參數還可以反過來用。# 使用 * 來展開元組,使用 ** 來展開關鍵字參數。args = (1, 2, 3, 4)kwargs = {"a": 3, "b": 4}all_the_args(*args) # equivalent to foo(1, 2, 3, 4) # 相當于 all_the_args(1, 2, 3, 4)all_the_args(**kwargs) # equivalent to foo(a=3, b=4) # 相當于 all_the_args(a=3, b=4)all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # 相當于 all_the_args(1, 2, 3, 4, a=3, b=4) # Python has first class functions# 函數在 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# 還有匿名函數(lambda x: x > 2)(3) #=> True # There are built-in higher order functions# 還有一些內建的高階函數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# 我們可以使用列表推導式來模擬 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. 類#################################################### # We subclass from object to get a class.# 我們可以從對象中繼承,來得到一個類。class Human(object): # A class attribute. It is shared by all instances of this class # 下面是一個類屬性。它將被這個類的所有實例共享。 species = "H. sapiens" # Basic initializer # 基本的初始化函數(構造函數) def __init__(self, name): # Assign the argument to the instance's name attribute # 把參數賦值為實例的 name 屬性 self.name = name # An instance method. All methods take self as the first argument # 下面是一個實例方法。所有方法都以 self 作為第一個參數。 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 # 類方法會被所有實例共享。 # 類方法在調用時,會將類本身作為第一個函數傳入。 @classmethod def get_species(cls): return cls.species # A static method is called without a class or instance reference # 靜態方法在調用時,不會傳入類或實例的引用。 @staticmethod def grunt(): return "*grunt*" # Instantiate a class# 實例化一個類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# 調用我們的類方法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# 調用靜態方法Human.grunt() #=> "*grunt*" ###################################################### 6. Modules## 6. 模塊#################################################### # You can import modules# 你可以導入模塊import mathprint math.sqrt(16) #=> 4 # You can get specific functions from a module# 也可以從一個模塊中獲取指定的函數from math import ceil, floorprint ceil(3.7) #=> 4.0print floor(3.7) #=> 3.0 # You can import all functions from a module.# Warning: this is not recommended# 你可以從一個模塊中導入所有函數# 警告:不建議使用這種方式from math import * # You can shorten module names# 你可以縮短模塊的名稱import math as mmath.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 文件。# 你可以編寫你自己的模塊,然后導入它們。# 模塊的名稱與文件名相同。 # You can find out which functions and attributes# defines a module.# 你可以查出一個模塊里有哪些函數和屬性import mathdir(math)Source File: adambard/learnxinyminutes-docs - GitHub
Translated by: cssmagic
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答