Python 基礎語法概覽

EusebiaConc 7年前發布 | 12K 次閱讀 Python Python開發

我是最近才開始接觸 Python 的,之前只是聽說過,但從來沒有親手用過。直到最近學習了之后,立馬愛上了這個簡潔優雅的語言,真后悔沒早點開始學習它。

之前在學校學的 C/C++、Java 等現在大部分都忘得差不多了,并且也不太喜歡這些強類型語言。編寫起來很麻煩,一點都不靈活。

用的第一個靈活的編程語言是 JavaScript,你懂的,前端必會的。現在學了 Python,感覺它比 JavaScript 更加靈活。哈哈,兩個我都要了啊。

自認為 JavaScript 學的還不錯,所以在最近學 Python 的時候發現兩者之間的語法上其實是有很多的共同點的。eg:Python 的字典 vs JavaScript 的對象。并且在學習 ES6 的時候,發現里面很多新型的語法與 Python 的語法很像(比如迭代器、乘方運算符等),應該是 ES6 從 Python 這里借鑒過去的吧。 ^_^

Python 簡介

Python是一種面向對象、 解釋型 的計算機程序設計語言。它使用 縮進 來定義語句塊。

Python的設計哲學是“優雅”、“明確”、“簡單”。

# shell 下顯示 Python 格言

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

應用領域:網絡爬蟲、網站開發、GUI開發、數據挖掘、機器學習、自然語言處理等。

小提示:在 Python shell 下,通過 help() 可查看當前變量的幫助信息(比如有哪些方法、屬性等)

字符編碼

  • 對于單個字符的編碼,Python 提供了 ord() 函數獲取字符 Unicode 編碼的整數表示, chr() 函數把編碼轉換為對應的字符
ord('¥')   => 65509
chr(25991)  => '文'
  • 由于 Python 的字符串類型是 str,在內存中以 Unicode 表示,一個字符對應若干個字節。如果要在網絡上傳輸,或者保存到磁盤上,就需要把 str 變為以字節為單位的 bytes。(使用 encode() 編碼 和 decode() 解碼 )
s = '死亡如風'
b = s.encode('utf-8') 
print(b) => b'\xe6\xad\xbb\xe4\xba\xa1\xe5\xa6\x82\xe9\xa3\x8e'
s.encode('ascii') => 報錯
b.decode('utf-8') => '死亡如風'

數據類型(另起文章)

下面只列出了常見的數據類型,全部數據類型 。

  • 布爾值(True、False)
  • 整數(int)
  • 小數(float)
  • 字符串(str)
  • 列表(list):類似于數組
  • 元組(tuple):類似于 list,不同的是 tuple 一旦初始化,便不能再進行改動
  • 集合(set):一組鍵的集合
  • 字典(dict)一組鍵值對的集合,類似 JavaScript 中的對象
  • 迭代器(Iterator)

操作符

  • 普通除: / , 平板除: // 。 平板除的結果只保留整數部分
5 // 2    => 2
5.0 // 2  => 2.0
  • 乘方運算符: ** 。eg:2**3 = 8

  • 賦值運算符: += 、 -= 、 **= 、 //= 、 %= 等。

    • 注意: Python 中沒有自減(a–)或自增(a++)運算符
  • 邏輯運算符: and 、 or 、 not

  • 成員運算符: in 、 not in ,可用于字符串、list、tuple 等

'w' in 'hello world'             => True
'apple' in ['a','bbb','apple']   => True
's' not in 'abc'                 => True
  • 身份運算符: is 、 is not ,用于比較兩個對象的存儲單元
    • 注意區分 is 與 == , is not 與 !=
    • is 用來判斷兩個變量的地址是否相同(可通過內置函數 id() 獲取指定對象的地址標識符)
    • == 用來判斷兩個變量的值是否相同
a = {'name':'percy'}
b = {'name':'percy'}
id(a)    => 645668157576 # 每次可能會不一樣
id(b)    => 645668535560
a is b   => False
a == b   => True

c = 20
d = 20
c is d   => True
c == d   => True
  • 位運算符: & (按位與)、 | (按位或)、 ^ (按位異或)、 - (按位取反)、 >> (右移)、 << (左移)

語句

  • if語句: 當條件成立時運行語句塊。經常與else, elif(相當于else if)配合使用。
a = 5
if a > 8:
    print('a > 8')
elif a < 4:
    print('a < 4')
else:
    print('4 <= a <= 8')
  • for…in 語句: 遍列列表、字符串、字典、集合等迭代器,依次處理迭代器中的每個元素,可配合 break 、 continue 使用
  • while 語句: 當條件為真時,循環運行語句塊。
  • class 語句: 用于定義類型。
  • def 語句: 用于定義函數和類型的方法。
  • pass 語句: 表示此行為空,不運行任何操作。
  • assert 語句: 又稱 斷言 ,用于程序調適階段時測試運行條件是否滿足。
n = int(input())
assert n != 0, 'n is zero!'

# 如果斷言失敗,assert 語句本身就會拋出 AssertionError
  • with 語句: Python2.6以后定義的語法,在一個場景中運行語句塊。比如,運行語句塊前加鎖,然后在語句塊運行結束后釋放鎖。
# 比如使用 with 語句操作文件,可以省略寫關閉文件語句

with open('1.txt','r',encoding='utf-8') as f:
    content = f.read()
  • yield 語句: 在迭代器函數內使用,用于返回一個元素。自從Python 2.5版本以后。這個語句變成一個運算符。
  • try 語句:exceptfinally 配合使用處理在程序運行中出現的異常情況。
  • raise 語句: 拋出一個異常。
// 方式一
try:
    10 / 0
except ZeroDivisionError as e:
    print('Error: %s' % e)
finally:
    print('Finally statement: 發生了某些錯誤')

// 方式二
try:
    10 / 0
except ZeroDivisionError as e:
    raise ValueError('Error: value error,哈哈')
finally:
    print('Finally statement: 發生了某些錯誤')
  • import 語句: 導入一個模塊或包。
# 常見的引入模塊的寫法
import module

import module as name

from module import name

from module import name as anothername

表達式

  • 最基本的表達式(a and b、a + b、a // b 等)
  • 字典、集合、列表的推導式
[x + 3 for x in range(4)]   => [3, 4, 5, 6]
{x + 3 for x in range(4)}   => {3, 4, 5, 6}
(x + 3 for x in range(4))   => 這里變成了一個生成器對象

d = {'num'+str(x): x for x in range(4)}
d => {'num0': 0, 'num3': 3, 'num1': 1, 'num2': 2}

l = [x*x for x in range(1,11) if x%2 == 0]
l => [4, 16, 36, 64, 100]

l = [m+n for m in 'ABC' for n in 'XY']
l => ['AX', 'AY', 'BX', 'BY', 'CX', 'CY']
  • 匿名函數表達式( lambda )
add = lambda x, y : x + y
add(1,4)  => 5
  • Python 中的條件表達式, x if condition else y ,類似于 C 語言中的 condition ? x : y
a = 'xxx' if {} else 'yyy'
a => 'yyy'
  • 切片表達式 ,主要用于切割數據,支持的數據類型有: str 、 bytes 、 list 、 tuple 等。
# 語法 s[left:right:step]

l = list(range(1,100))
l[:]      => [1, 2 ... ,99]
l[96:]    => [97, 98, 99]
l[:3]     => [1, 2, 3]
l[3:6]    => [4, 5, 6]
l[::20]   => [1, 21, 41, 61, 81]
l[:10:2]  => [1, 3, 5, 7, 9]
# 翻轉一個字符串

s = 'hello world'
s[::-1]   => 'dlrow olleh'

函數

為了增強代碼的可讀性,可以在函數后書寫“文檔字符串”(Documentation Strings,或者簡稱docstrings),用于解釋函數的作用、參數的類型與意義、返回值類型與取值范圍等。可以使用內置函數help()打印出函數的使用幫助。

deftest():
    'Text on this line is to introduce this function'
    print('A test function')

help(test)

函數名

函數名只是指向函數對象的引用。( 雖然可以更改內置函數,但是不推薦更改,所以請盡量不要使用與 Python 關鍵字、內置函數名名稱相同的變量名 )

abs(-11)   => 11
aaa = abs
aaa(-12)   => 12
abs = 'a'
abs(-13)   => 報錯

函數參數

  • 必選參數(缺一不可)
defadd(a,b):
    return a+b

add(1)    => 報錯
add(1,2)  => 3
  • 默認參數(必選參數在前,默認參數在后)
defadd(a,b=5):
    return a+b

add(1)    => 6
add(1,2)  => 3
  • 可變參數(在傳入 list、tuple 時,注意在前面加個星號)

可變參數允許你傳入0個或任意個參數,這些可變參數在函數調用時自動組裝為一個 tuple。

defadd(*numbers):
    print(type(numbers))       # <class 'tuple'>
    sum = 0
    for number in numbers:
        sum += number
    return sum

add(1)                => 1
add(1,2,3)            => 6
add(*[1,2,3,4,5])     => 15
add(*(11,22,33))      => 66
  • 關鍵字參數

關鍵字參數允許你傳入0個或任意個含參數名的參數,這些關鍵字參數在函數內部自動組裝為一個 dict。

deffunc(**keywords):
    print(keywords)

func()                    => {}
func(name='percy')        => {'name': 'percy'}
func(name='percy',age=22) => {'age': 22, 'name': 'percy'}

如果要限制關鍵字參數的名字,就可以用命名關鍵字參數。命名關鍵字參數需要一個特殊分隔符 * , * 后面的參數被視為命名關鍵字參數。

deffunc(*,name):
    print(name)

func()                    => 報錯
func(name='percy')        => percy
func(name='percy',age=22) => 報錯

如果函數定義中已經有了一個可變參數,后面跟著的命名關鍵字參數就不再需要一個特殊分隔符 * 了。

deffunc(*numbers,name):
    print(name)

func()                    => 報錯
func(name='percy')        => percy
func(name='percy',age=22) => 報錯
  • 上面的四種參數可以組合使用,但是要注意順序。 參數定義的順序必須是:必選參數、默認參數、可變參數、命名關鍵字參數和關鍵字參數。

函數返回值

  • 函數執行完畢也沒有 return 語句時,自動 return None

  • 看下面代碼,函數居然可以返回多個值。。。

import random
defmove():
    x = random.randrange(100) # 0-100 隨機整數
    y = random.randrange(100) # 0-100 隨機整數
    return x,y

rX,rY = move()
rX  => 54
rY  => 61

其實這只是一種假象,Python 函數返回的仍然是單一值,只不過這個值是一個 tuple 對象。 在語法上,返回一個 tuple 可以省略括號,而多個變量可以同時接收一個 tuple,按位置賦給對應的值 (有點像 ES6 的解構賦值,哈哈)

就到這兒吧,剩下的陸續更新。

 

來自:http://blog.percymong.com/2017/03/21/python-basic-grammar/

 

 本文由用戶 EusebiaConc 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!