輕輕鬆鬆搞定Python基本知識小結

Python是一門具有強類型(即變量類型是強制要求的)、動態性、隱式類型(不需要做變量聲明)、大小寫敏感(var和VAR代表了不同的變量)以及面向對象(一切皆爲對象)等特點的編程語言。python語言簡潔,易學。


語法

Python中沒有強制的語句終止字符,且代碼塊是通過縮進來指示的。縮進表示一個代碼塊的開始,逆縮進則表示一個代碼塊的結束。

聲明以冒號(:)字符結束,並且開啓一個縮進級別。

單行註釋以井號字符(#)開頭,多行註釋則以多行字符串的形式出現。

賦值(事實上是將對象綁定到名字)通過等號(“=”)實現,雙等號(“==”)用於相等判斷,”+=”和”-=”用於增加/減少運算(由符號右邊的值確定增加/減少的值)。這適用於許多數據類型,包括字符串。你也可以在一行上使用多個變量。例如:

>>> mystring = "Hello"
>>> mystring += " world."
>>> print mystring
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar

數據類型

Python具有列表(list)、元組(tuple)和字典(dictionaries)三種基本的數據結構。列表list的特點跟一維數組類似(當然你也可以創建類似多維數組的“列表的列表”),字典則是具有關聯關係的數組(通常也叫做哈希表),而元組tuple則是不可變的一維數組(Python中“數組”可以包含任何類型的元素,這樣你就可以使用混合元素,例如整數、字符串或是嵌套包含列表、字典或元組)。

數組中第一個元素索引值(下標)爲0,使用負數索引值能夠從後向前訪問數組元素,-1表示最後一個元素。數組元素還能指向函數。來看下面的用法:

>>> sample = [1, ["another", "list"], ("a", "tuple")] #列表的列表

>>> mylist = ["List item 1", 2, 3.14]   #列表

>>> mylist[0] = "List item 1 again" # We're changing the item.

>>> mylist[-1] = 3.14 # Here, we refer to the last item.

>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}#字典

>>> mydict["pi"] = 3.15 # This is how you change dictionary values.

>>> mytuple = (1, 2, 3) #元組

>>> print len(mylist)#查看列表的字符數

3

字符串

python中字符串使用單引號或是雙引號來表示,並且還能夠在通過某一種標示的字符串中使用另外一種標示符(例如 “He said ‘hello’.”)。多行字符串可以通過三個連續的單引號或是雙引號來進行標示。

Python可以通過u”This is a unicode string”這樣的語法使用Unicode字符串。

如果想通過變量來填充字符串,可以使用取模運算符(%)和一個元組。使用方式是在目標字符串中從左至右使用%s來指代變量的位置,或者使用字典來代替,示例如下:

# WARNING: Watch out for the trailing s in "%(key)s".

>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}

This is a test.

流程控制

Python中可以使用if、for和while來實現流程控制。Python中並沒有select,取而代之使用if來實現。使用for來枚舉列表中的元素。如果希望生成一個由數字組成的列表,則可以使用range(<number>)函數。以下是這些聲明的語法示例:

rangelist=range(10)
>>>printrangelist
[0,1,2,3,4,5,6,7,8,9]

#for循環語句
fornumberinrangelist:
    # Check if number is one of
    # the numbers in the tuple.
    ifnumberin(3,4,7,9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass# Do nothing

#if條件選擇
ifrangelist[1]==2:
    print"The second item (lists are 0-based) is 2"
elifrangelist[1]==3:
    print"The second item (lists are 0-based) is 3"
else:
    print"Dunno"

#while循環 
whilerangelist[1]==1:
    pass

函數

函數通過“def”關鍵字進行聲明。可選參數以集合的方式出現在函數聲明中並緊跟着必選參數,可選參數可以在函數聲明中被賦予一個默認值。已命名的參數需要賦值。函數可以返回一個元組(使用元組拆包可以有效返回多個值)。

Lambda函數是由一個單獨的語句組成的特殊函數,參數通過引用進行傳遞,但對於不可變類型(例如元組,整數,字符串等)則不能夠被改變。這是因爲只傳遞了該變量的內存地址,並且只有丟棄了舊的對象後,變量才能綁定一個對象,所以不可變類型是被替換而不是改變(譯者注:雖然Python傳遞的參數形式本質上是引用傳遞,但是會產生值傳遞的效果)。例如:

#lambda舉例
# 作用等同於 def funcvar(x): return x + 1
funcvar=lambdax:x+1
>>>printfuncvar(1)
2
 

# an_int 和 a_string 是可選參數,它們有默認值
# 如果調用 passing_example 時只指定一個參數,那麼 an_int 缺省爲 2 ,a_string 缺省爲 A default string。如果調用 passing_example 時指定了前面兩個參數,a_string 仍缺省爲 A default string。
# a_list 是必備參數,因爲它沒有指定缺省值。
defpassing_example(a_list,an_int=2,a_string="A default string"):
    a_list.append("A new item")
    an_int=4
    returna_list,an_int,a_string
 
>>>my_list=[1,2,3]
>>>my_int=10
>>>printpassing_example(my_list,my_int)
([1,2,3,'A new item'],4,"A default string")
>>>my_list
[1,2,3,'A new item']
>>>my_int
10

Python支持有限的多繼承形式。私有變量和方法可以通過添加至少兩個前導下劃線和最多尾隨一個下劃線的形式進行聲明(如“__spam”,這只是慣例,而不是Python的強制要求)。當然,我們也可以給類的實例取任意名稱。例如:

class MyClass(object):
    common = 10
    def __init__(self):
        self.myvariable = 3
    def myfunction(self, arg1, arg2):
        return self.myvariable


    # This is the class instantiation
>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all classes.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50

文件I / O

Python針對文件的處理有很多內建的函數庫可以調用。例如,這裏演示瞭如何序列化文件(使用pickle庫將數據結構轉換爲字符串):

import pickle
mylist=["This","is",4,13327]
# Open the file C:\\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile=open(r"C:\\binary.dat","w")
pickle.dump(mylist,myfile)
myfile.close()
 
myfile=open(r"C:\\text.txt","w")
myfile.write("This is a sample string")
myfile.close()
 
myfile=open(r"C:\\text.txt")
>>>print myfile.read()
'This is a sample string'
myfile.close()
 
# Open the file for reading.
myfile=open(r"C:\\binary.dat")
loadedlist=pickle.load(myfile)
myfile.close()
>>>print loadedlist
['This','is',4,13327]

其它雜項

  • 數值判斷可以鏈接使用,例如 1<a<3 能夠判斷變量 a 是否在1和3之間。
  • 可以使用 del 刪除變量或刪除數組中的元素。
  • 列表推導式(List Comprehension)提供了一個創建和操作列表的有力工具。列表推導式由一個表達式以及緊跟着這個表達式的for語句構成,for語句還可以跟0個或多個if或for語句,來看下面的例子:

>>>lst1=[1,2,3]
>>>lst2=[3,4,5]
>>>print[x*y for x in lst1 for y in lst2]
[3,4,5,6,8,10,9,12,15]
>>>print[x for x in lst1 if 4>x>1]
[2,3]
# Check if an item has a specific property.
# "any" returns true if any item in the list is true.
>>>any([i % 3 for i in [3,3,4,4,3]])
True
# This is because 4 % 3 = 1, and 1 is true, so any()
# returns True.
 
# Check how many items have this property.
>>>sum(1 for i in [3,3,4,4,3] if i==4)
2
>>>del lst1[0]
>>>print lst1
[2,3]
>>>del lst1

全局變量在函數之外聲明,並且可以不需要任何特殊的聲明即能讀取,但如果你想要修改全局變量的值,就必須在函數開始之處用global關鍵字進行聲明,否則Python會將此變量按照新的局部變量處理(請注意,如果不注意很容易被坑)。例如:
number=5
 
def myfunc():
    # This will print 5.
    print number
 
def anotherfunc():
    # This raises an exception because the variable has not
    # been bound before printing. Python knows that it an
    # object will be bound to it later and creates a new, local
    # object instead of accessing the global one.
    print number
    number=3
 
def yetanotherfunc():
    globalnumber
    # This will correctly change the global.
    number=3

參考:http://blog.jobbole.com/43922/


發佈了49 篇原創文章 · 獲贊 21 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章