Python是基礎
前言
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 name
,print(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語句ifscore = 75
if score>=60:
print 'passed'
登入後複製
兩次回車,即可執行程式碼。 if-elsescore = 75 if score>=60: print 'passed'
if score>=60:
print('passed')
else:
print('failed')
登入後複製
if-elif-elseif score>=60: print('passed') else: print('failed')
if score>=90:
print('excellent')
elif score>=80:
print('good')
elif score>=60:
print('passed')
else:
print('failed')
登入後複製
循環for循環if score>=90: print('excellent') elif score>=80: print('good') elif score>=60: print('passed') else: print('failed')
L = [75, 92, 59, 68]
sum = 0.0
for score in L:
sum += score
print(sum / 4)
登入後複製
while循環L = [75, 92, 59, 68] sum = 0.0 for score in L: sum += score print(sum / 4)
sum = 0
x = 1
while x<100:
sum += x
x = x + 1
print(sum)
登入後複製
rrsum = 0 x = 1 while x<100: sum += x x = x + 1 print(sum)
sum = 0
x = 1
while True:
sum = sum + x
x = x + 1
if x > 100:
break
print(sum)
登入後複製while循環
sum = 0 x = 1 while True: sum = sum + x x = x + 1 if x > 100: break print(sum)
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)
for x in ['A', 'B', 'C']: for y in ['1', '2', '3']: print(x + y)
d = {
'Adam': 95,
'Lisa': 85,
'Bart': 59,
'Paul': 75
}
print(d)
print(d['Adam'])
print(d.get('Lisa'))
d['voidking']=100
print(d)
for key in d:
print(key+':',d.get(key))
登入後複製s = set(['Adam', 'Lisa', 'Bart', 'Paul'])
print(s)
s = set(['Adam', 'Lisa', 'Bart', 'Paul', 'Paul'])
print(s)
len(s)
print('Adam' in s)
print('adam' in s)
for name in s:
print(name)
登入後複製s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])
for x in s:
print(x[0]+':',x[1])
登入後複製
函數自帶函數d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 75 } print(d) print(d['Adam']) print(d.get('Lisa')) d['voidking']=100 print(d) for key in d: print(key+':',d.get(key))
s = set(['Adam', 'Lisa', 'Bart', 'Paul']) print(s) s = set(['Adam', 'Lisa', 'Bart', 'Paul', 'Paul']) print(s) len(s) print('Adam' in s) print('adam' in s) for name in s: print(name)
s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)]) for x in s: print(x[0]+':',x[1])
s.add(100)
print(s)
s.remove(('Adam',95))
print(s)
登入後複製
自訂函數s.add(100) print(s) s.remove(('Adam',95)) print(s)
del sum
L = [x*x for x in range(1,101)]
print sum(L)
登入後複製
引入函式庫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 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))
字串切片
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
L = ['Adam', 'Lisa', 'Bart', 'Paul'] L[0:3] L[:3] L[1:3] L[:] L[::2]
L = ['Adam', 'Lisa', 'Bart', 'Paul'] for index, name in enumerate(L): print(index+1, '-', name) myList = zip([100,20,30,40],L); for index, name in myList: print(index, '-', name)
迭代dict的value
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 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 = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } for key, value in d.items(): print(key, ':', value)
列表生成
一般表达式
L = [x*(x+1) for x in range(1,100)] print(L)
复杂表达式
d = { 'Adam': 95, 'Lisa': 85, 'Bart': 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中文网!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

VS Code可以在Windows 8上運行,但體驗可能不佳。首先確保系統已更新到最新補丁,然後下載與系統架構匹配的VS Code安裝包,按照提示安裝。安裝後,注意某些擴展程序可能與Windows 8不兼容,需要尋找替代擴展或在虛擬機中使用更新的Windows系統。安裝必要的擴展,檢查是否正常工作。儘管VS Code在Windows 8上可行,但建議升級到更新的Windows系統以獲得更好的開發體驗和安全保障。

VS Code 可用於編寫 Python,並提供許多功能,使其成為開發 Python 應用程序的理想工具。它允許用戶:安裝 Python 擴展,以獲得代碼補全、語法高亮和調試等功能。使用調試器逐步跟踪代碼,查找和修復錯誤。集成 Git,進行版本控制。使用代碼格式化工具,保持代碼一致性。使用 Linting 工具,提前發現潛在問題。

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。

VS Code 擴展存在惡意風險,例如隱藏惡意代碼、利用漏洞、偽裝成合法擴展。識別惡意擴展的方法包括:檢查發布者、閱讀評論、檢查代碼、謹慎安裝。安全措施還包括:安全意識、良好習慣、定期更新和殺毒軟件。
