首頁  >  文章  >  後端開發  >  Python是基礎

Python是基礎

高洛峰
高洛峰原創
2017-02-16 11:22:281551瀏覽

前言

Python,是龜叔在1989年為了打發無聊的聖誕節而編寫的一門程式語言,特點是優雅、明確、簡單,現今擁有豐富的標準庫和第三方函式庫。
Python適合開發Web網站和各種網路服務,系統工具和腳本,作為「膠水」語言把其他語言開發的模組包裝起來使用,科學計算等等。

小編學習Python的理由有三:
為了爬取所需的各種數據,不妨學習Python。
為了分析數據和挖掘數據,不妨學習Python。
為了做一些好玩有趣的事,不妨學習Python。

準備工作

1、在Python官網下載安裝喜歡的版本,小編使用的,是目前最新版本3.6.0。

2、開啟IDLE,這是Python的整合開發環境,儘管簡單,但極為有用。 IDLE包括一個能夠利用顏色突出顯示語法的編輯器、一個調試工具、Python Shell,以及一個完整的Python3在線文檔集。

hello world

1、在IDLE中,輸入print('hello world'),回車,則列印出hello world。
PS:語句最後加上不加分號;都可以,小編決定不加分號,比較簡單。

2、使用sublime新檔案hello.py,內容如下:

print('hello world')

在Windows下,shift+右鍵,在此處開啟指令窗口,執行python hello.py,回車,則列印出hello world。

3、使用sublime新建檔案hello.py,內容如下:

#!/usr/bin/env python
print('hello world')

在Linux或Mac環境下,可以直接執行腳本。首先新增執行權限chmod a+x hello.py,然後執行./hello.py。當然,也可以跟Windows一樣,使用python hello.py來執行腳本。

引入模組

1、新建name.py,內容如下:

name='voidking'

2、執行python name.py
3、進入python shell模式,執行import nameprint(name.name),則印出voidking。

基礎語法

常用函數(print)、資料型態、表達式、變數、條件與迴圈、函數。和其他語言類似,下面選擇一部分展開。

list鍊錶數組

1、定義數組
myList = ['Hello', 100, True]
2、輸出數組
print(myList)
2、輸出數組
print(myList)2、輸出數組
print(myList)
3、輸出數組元素 ])

print(myList[-1])4、追加元素到末尾

myList.append('vomying')5、追加元素到頭部myList.insert(0idking. ')

6、刪除元素myList.pop()

myList.pop(0)

7、元素賦值
myList[0]='hello666'
myList[0]='hello666'定義陣列
myTuple = ('Hello', 100, True)
錯誤定義:myTuple1=(1)
,正確定義:
myTuple=(1,)2、輸出陣列

3、輸出陣列元素print(myTuple[0])4、tuple和list結合

t = ('a', 'b', ['A', 'B'])

t[2][0]='X'

if語句

if

score = 75
if score>=60:
    print 'passed'

兩次回車,即可執行程式碼。

if-else

if score>=60:
    print('passed')
else:
    print('failed')

if-elif-else

if score>=90:
    print('excellent')
elif score>=80:
    print('good')
elif score>=60:
    print('passed')
else:
    print('failed')

循環

for循環

L = [75, 92, 59, 68]
sum = 0.0
for score in L:
       sum += score
print(sum / 4)

while循環

sum = 0
x = 1
while x<100:
    sum += x
    x = x + 1
print(sum)

rr

sum = 0
x = 1
while True:
    sum = sum + x
    x = x + 1
    if x > 100:
        break
print(sum)
while循環

L = [75, 98, 59, 81, 66, 43, 69, 85]
sum = 0.0
n = 0
for x in L:
    if x < 60:
        continue
    sum = sum + x
    n = n + 1
print(sum/n)

dict的功能是建立一組key和一組value的映射關係。

for x in [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]:
    for y in [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;]:
        print(x + y)

set

set持有一系列元素,這一點和list很像,但是set的元素沒有重複,而且是無序的,這點和dict的key很像。

d = {
    &#39;Adam&#39;: 95,
    &#39;Lisa&#39;: 85,
    &#39;Bart&#39;: 59,
    &#39;Paul&#39;: 75
}
print(d)
print(d[&#39;Adam&#39;])
print(d.get(&#39;Lisa&#39;))
d[&#39;voidking&#39;]=100
print(d)
for key in d:
    print(key+&#39;:&#39;,d.get(key))
s = set([&#39;Adam&#39;, &#39;Lisa&#39;, &#39;Bart&#39;, &#39;Paul&#39;])
print(s)
s = set([&#39;Adam&#39;, &#39;Lisa&#39;, &#39;Bart&#39;, &#39;Paul&#39;, &#39;Paul&#39;])
print(s)
len(s)
print(&#39;Adam&#39; in s)
print(&#39;adam&#39; in s)
for name in s:
    print(name)
s = set([(&#39;Adam&#39;, 95), (&#39;Lisa&#39;, 85), (&#39;Bart&#39;, 59)])
for x in s:
    print(x[0]+&#39;:&#39;,x[1])

函數

自帶函數

s.add(100)
print(s)
s.remove((&#39;Adam&#39;,95))
print(s)

自訂函數

del sum
L = [x*x for x in range(1,101)]
print sum(L)

引入函式庫

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x
my_abs(-100)
可變參數

import math

def quadratic_equation(a, b, c):
    x = b * b - 4 * a * c
    if x < 0:
        return none
    elif x == 0:
        return -b / (2 *a)
    else:
        return ((math.sqrt(x) - b ) / (2 * a)) , ((-math.sqrt(x) - b ) / (2 * a))
print(quadratic_equation(2, 3, 0))
print(quadratic_equation(1, -6, 5))

切片

有序的list,預設以函數形式表示,執行range函數,即可以以list形式表示。

字串切片

def average(*args):
    if args:
        return sum(args)*1.0/len(args)
    else:
        return 0.0

print(average())
print(average(1, 2))
print(average(1, 2, 2, 3, 4))

迭代

Python的for循環不僅可以用在list或tuple上,還可以作用在其他任何可迭代物件上。

迭代運算就是對於一個集合,無論該集合是有序或無序,我們用for迴圈總是可以依序取出集合的每一個元素。

集合是指包含一組元素的資料結構,包括:

    有序集合:list,tuple,str和unicode;
  • 無序集合:set
  • 無序集合:setkey

無序集合value對:dict

L = [&#39;Adam&#39;, &#39;Lisa&#39;, &#39;Bart&#39;, &#39;Paul&#39;]
L[0:3]
L[:3]
L[1:3]
L[:]
L[::2]

索引迭代🎜🎜對於有序集合,元素是有索引的,如果我們想在for循環中拿到索引,怎麼辦?方法是使用enumerate()函數。 🎜
L = [&#39;Adam&#39;, &#39;Lisa&#39;, &#39;Bart&#39;, &#39;Paul&#39;]
for index, name in enumerate(L):
    print(index+1, &#39;-&#39;, name)

myList = zip([100,20,30,40],L);
for index, name in myList:
    print(index, &#39;-&#39;, name)

迭代dict的value

d = { &#39;Adam&#39;: 95, &#39;Lisa&#39;: 85, &#39;Bart&#39;: 59 }
print(d.values())
for v in d.values():
    print(v)

PS:Python3.x中,dict的方法dict.keys(),dict.items(),dict.values()不会再返回列表,而是返回一个易读的“views”。这样一来,k = d.keys();k.sort()不再有用,可以使用k = sorted(d)来代替。
同时,dict.iterkeys(),dict.iteritems(),dict.itervalues()方法不再支持。

迭代dict的key和value

d = { &#39;Adam&#39;: 95, &#39;Lisa&#39;: 85, &#39;Bart&#39;: 59 }
for key, value in d.items():
    print(key, &#39;:&#39;, value)

列表生成

一般表达式

L = [x*(x+1) for x in range(1,100)]
print(L)

复杂表达式

d = { &#39;Adam&#39;: 95, &#39;Lisa&#39;: 85, &#39;Bart&#39;: 59 }
def generate_tr(name, score):
    if score >=60:
        return '<tr><td>%s</td><td>%s</td></tr>' % (name, score)
    else:
        return '<tr><td>%s</td><td style="color:red">%s</td></tr>' % (name, score)

tds = [generate_tr(name,score) for name, score in d.items()]
print('<table border="1">')
print('<tr><th>Name</th><th>Score</th><tr>')
print('\n'.join(tds))
print('</table>')

条件表达式

L = [x * x for x in range(1, 11) if x % 2 == 0]
print(L)
def toUppers(L):
    return [x.upper() for x in L if isinstance(x,str)]

print(toUppers(['Hello', 'world', 101]))

多层表达式

L = [m + n for m in 'ABC' for n in '123']
print(L)
L = [a*100+b*10+c for a in range(1,10) for b in range(0,10) for c in range(1,10) if a==c]
print(L)

后记

至此,Python基础结束。接下来,爬虫飞起!

更多Python,基础相关文章请关注PHP中文网!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn