Installing Python 3 - How to install/use both Python 2 and Python 3 https://www.youtube.com/watch?v=IX6mc9l6tY4&index=2&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M python官網: www.python.org 開始>python shell窗口 輸入print('hi') print('Hi',5) #輸出Hi5 print('we\'re going to the store') #\後字符原樣輸出 print('Hi'+str(5)) #str()方法, int('8') 4**4 #輸出256, 表示4的4次方 x,y = (3,8) #x=3, y=8 for eachNumber in exampleList #至關於c#中的foreach rang(1,11) #輸出1到10 格式化字符串函數format: "蘋果的花費爲:{};葡萄的話費爲:{};總花費爲:{}".format(apple_cost,grape_cost,total_cost) 變量交換值: a = 10 b = 20 a, b = b, a #結果爲a is 20, b is 10 if z<y>x: print('y is greater than z and greater than x') if x>y: print('111') elif x<z: #elif, else if的寫法 print('222') else: print('333') def simple(num1,num2=5): print(num1,num2) simple(2) #輸出2 5, num2默認值爲5,方法中能夠只傳一個沒有默認值的參數 有多個默認值參數,調用方法: basic_window(500,350,bgc='b') Python 3 Programming Tutorial - Global and Local Variables https://www.youtube.com/watch?v=r9LtArXOYjk&index=14&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M 使用全局變量須要在方法裏面聲明: x=6 def example(): global x #這裏聲明x爲全局變量 print(x) x+=5 print(x) Python 3 Programming Tutorial - Installing modules https://www.youtube.com/watch?v=UKXx4e9PotI&index=15&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M Python Extension Packages: www.lfd.uci.edu/~gohlke/pythonlibs/ PyQtGraph: www.pyqtgraph.org 下載pyqtgraph-0.9.8.tar.gz解壓, 文件夾右鍵打開命令窗口執行setup.py install(有setup.py文件). How to download and install Python Packages and Modules with Pip https://www.youtube.com/watch?v=jnpC_Ib_lbc&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=16 使用指定的Python版本: C:/Python34/Scripts/pip install matplotlib PyPI - the Python Package Index: https://pypi.python.org/pypi https://www.lfd.uci.edu/~gohlke/pythonlibs/ 下載所需的package(.whl), 打開命令窗口輸入pip install "xxx.whl" print('\n') #\n換行 readMe = open('exampleFile.txt','r').readlines() #這裏的readlines()返回數組如['111','222','333'], 若是是read()方法則返回字符串 print(readMe) if __name__ == '__main__': #若是是執行的本腳本則會打印test,若是是執行的其餘腳本引用了本腳本則不會打印test print('test') Getting user input: x = input('What is your name?') print('Hello',x) Python 3 Programming Tutorial - Statistics (Mean, Standard Deviation) https://www.youtube.com/watch?v=D2U6yg0i-oA&index=24&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M 自身模塊存放路徑: C:/Python/Lib, 第三方package存放路徑: C:/Python/Lib/site-packages import statistics example_list = [4,2,3,5] x = statistics.variance(example_list) print(x) as: import statistics as s x = s.variance(example_list) 連簡寫都不要: from statistics import variance x = variance(example_list) Python 3 Programming Tutorial - Lists and Tuples https://www.youtube.com/watch?v=RVXIBZvg-W8&index=27&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M Tuples不能變,List能夠變. Tuples: x = 5,6,7 x = (5,6,7) print(x[1]) #輸出6 List: y = [5,6,7,8] Python 3 Programming Tutorial - List Manipulation https://www.youtube.com/watch?v=LUoKlnK5wcc&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=28 x = [5,7,3,4] x.append(2) #將2加到list的最後 x.insert(2,99) #插入到index爲2的位置,值是99 x.remove(2) #移除第一個元素爲2的元素 x.remove(x[2]) #移除第三個元素 print(x[2:3]) #輸出第3到第四個元素, 結果爲[3,4] print(x[-1]) #輸出最後一個元素 print(x[-2]) #輸出倒數第二個元素 print(x.index[7]) #輸出元素7的序列號,結果爲1 print(x.count[7]) #輸出有多少個元素7, 結果爲1 x.sort() Python 3 Programming Tutorial - Multi-dimensional List https://www.youtube.com/watch?v=Go-FfGhxbSM&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=29 x = [[5,6],[6,7],[7,2],[2,5]] print(x[1][0]) #第二個元素裏面的第一個元素, 結果爲6 Python 3 Programming Tutorial - Reading from a CSV spreadsheet https://www.youtube.com/watch?v=K_oXb04izZM&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=30 import csv with open('example.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: print(row) Python 3 Programming Tutorial - Try and Except error Handling https://www.youtube.com/watch?v=nqGhjLUhyDc&index=31&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M try: ... except Exception as e: print(e) if whatColor in colors: #if in Python 3 Programming Tutorial - Multi-line Print https://www.youtube.com/watch?v=gINlrLx2zNA&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=32 print(''' aaa bbb ccc ''') Python 3 Programming Tutorial - Dictionaries https://www.youtube.com/watch?v=YNRc6c0wUA8&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=33 exDict = {'Jack':15, 'Bob':22, 'Alice':12, 'Kevin':17} exDict['Tim'] = 14 #添加 exDict['Tim'] = 15 #修改 del exDict['Tim'] #刪除 Python 3 Programming Tutorial - Built-in Functions https://www.youtube.com/watch?v=7rjJrQy9gi4&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=34 exNum1 = -5 print(abs(exNum1)) #結果爲5 help() #ctrl + c退出 max(exList) #max函數 alt + p #輸出上一次打印的東西 int('55') str(55) Python 3 Programming Tutorial - OS Module https://www.youtube.com/watch?v=wgHeTJtth0w&index=35&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M import os curDir = os.getcwd() #get current working directory os.mkdir('newDir') import time time.sleep(2) os.rename('newDir','newDir2') tiem.sleep(2) os.rmdir('newDir2') help(os) Python 3 Programming Tutorial - Sys Module https://www.youtube.com/watch?v=rLG7Tz6db0w&index=36&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M import sys sys.stderr.write('This is stderr text\n') #紅色的文字 sys.stderr.flush() sys.stdout.write('This is stdout text\n') #藍色的文字 print(sys.argv) 文件夾右鍵打開命令窗口執行python sys.py(sys.py是python文件),便是執行這個python文件中的代碼. Python 3 Programming Tutorial - urllib module https://www.youtube.com/watch?v=5GzVNi0oTxQ&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=37 urllib module用於訪問網絡 import urllib.request import urllib.parse #x = urllib.request.urlopen('https://www.google.com') #print(x.read()) #打印google頁面的源代碼 url="http://pythonprogramming.net" values={'s':'basic','submit':'search'} #網址後面所帶的參數 data=urllib.parse.urlencode(values) data=data.encode('utf-8') req=urllib.request.Request(url,data) resp=urllib.request.urlopen(req) respData=resp.read() print(respData) Python 3 Programming Tutorial - Regular Expressions / Regex with re https://www.youtube.com/watch?v=sZyAn2TW7GY&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=38 import re #導入正則表達式的命名空間 #注意變量右邊是三個單引號 exampleString = ''' Jessica is 15 years old, and Daniel is 27 years old. Edward is 97, and his grandfather, Oscar, is 98. ''' ages = re.findall(r'\d{1,3}',exampleString) names = re.findall(r'[A-Z][a-z]*', exampleString) print(ages) print(names) ageDict = {} x=0 for eachName in names: ageDict[eachName] = ages[x] #至關於賦值給屬性 x+=1 print(ageDict) #結果爲 {'Daniel':'27','Jessica':'15',...} Python 3 Programming Tutorial - Parsing Websites with re and urllib https://www.youtube.com/watch?v=GEshegZzt3M&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=39 import urllib.request import urllib.parse import re url = 'http://pythonprogramming.net' values = {'s':'basics','submit':'search'} data = urllib.parse.urlencode(values) data = data.encode('utf-8') req = urllib.request.Request(url,data) resp = urllib.request.urlopen(req) respData = resp.read() print(respData) paragraphs=re.findall(r'<p>(.*?)</p>',str(respData)) for eachP in paragraphs: print(eachP) Python 3 Programming Tutorial - tkinter module making windows https://www.youtube.com/watch?v=Ccct5D2AyNM&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=40 image的libery: 打開www.lfd.uci.edu/~gohlke/pythonlibs/ 頁面搜索pillow, 打開www.lfd.uci.edu/~gohlke/pythonlibs/#pil,下載Pillow-2.5.1.win-amd64-py3.4.exe from tkinter import * from PIL import Image, ImageTk class Window(Frame): #Frame來自tkinter def __init__(self,master = None): Frame.__init__(self,master) self.master=master self.init_window() def init_window(self): self.master.title("GUI") self.pack(fill=BOTH, expand=1) #quitButton = Button(self, text="Quit",command=self.client_exit) #Button來自tkinter #quitButton.place(x=0,y=0) menu = Menu(self.master) self.master.config(menu=menu) file = Menu(menu) file.add_command(label='Exit',command=self.client_exit) #若是self.client_exit後面加上括號(),則會當即執行改方法 menu.add_cascade(label='File',menu=file) edit=Menu(menu) edit.add_command(label='Show Image', command=self.showImg) edit.add_command(label='Show Text', command=self.showTxt) menu.add_cascade(label='Edit',menu=edit) def showImg(self): load=Image.open('pic.png') render=imageTk.PhotoImage(load) img=Label(self,image=render) img.image=render img.place(x=0,y=0) def showTxt(self): text = Label(self, text='Hey there good lookin!') text.pack() def client_exit(self): exit() root = Tk() root.geometry("400*300") app = Window(root) root.mainloop() Python 3 Programming Tutorial - Threading module https://www.youtube.com/watch?v=NwH0HvMI4EA&index=45&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M import threading from queue import Queue import time print_lock = threading.Lock() def exampleJob(worker): time.sleep(0.5) with print_lock: print(threading.current_thread().name, worker) def threader(): while True: worker=q.get() exampleJob(worker) q.task_done() q = Queue() for x in rang(10): t = threading.Thread(target = threader) t.daemon = True t.start() start = time.time() for worker in rang(20): q.put(worker) q.join() print('Entire job took:',time.time()-start) Python 3 Programming Tutorial - cx freeze python to exe https://www.youtube.com/watch?v=GSoOwSqTSrs&index=46&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M cx freeze將程序打包成exe文件,網址: cx-freeze.sourceforge.net, 使用命令行或者下載安裝cx_Freeze-4.3.3.win-amd64-py3.4.exe (md5) setup.py: from cx_Freeze import setup, Executable setup(name='urlParse', version='0.1', description='Parse stuff', executables=[Executable("distme.py")] ) 打開命令窗口,cd到setup.py文件位置,執行命令: python setup.py build, 會建立一個build文件夾裏面包含生成的exe文件和運行所依賴的環境文件. Python 3 Programming Tutorial - Subprocess module https://www.youtube.com/watch?v=5XU-mAZVv4w&index=47&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M communicate from script to shell and get output from the shell. python import subprocess subprocess.call('python systut.py "check this out!"',shell=True) #輸出check this out! Python 3 Programming Tutorial - Matplotlib Graphing Intro https://www.youtube.com/watch?v=H72jSxkLQHQ&index=48&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M 官網: matplotlib.org/index.html 下載, 或者打開www.lfd.uci.edu/~gohlke/pythonlibs/頁面搜索matplotlib 下載安裝. from matplotlib import pyplot as plt from matplotlib import style #下載style.zip: pythonprogramming.net/downloads/style.zip, 將style文件夾放入項目根目錄下. style.use('ggplot') x = [5,6,7,8] y = [7,3,8,3] plt.grid(True, color='k') #plt.scatter(x,y,color='c',align='center') 點狀圖 #plt.bar(x,y,color='c',align='center') 柱狀圖 plt.plot(x,y,'g',linewidth=5, label='Line One') #'g'表明線的顏色是綠色,5表示線的粗細, label線的備註. plt.title('Epic Chart') plt.ylabel('Y axis') plt.xlabel('X axis') plt.legend() #跟上面的label='Line One'配套出現 plt.show() #打開一個圖形窗口 Python 3 Programming Tutorial - Matplotlib plotting from a CSV https://www.youtube.com/watch?v=MNLmQJtCCZY&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=53 from matplotlib import pyplot as plt from matplotlib import style import numpy as np style.use('ggplot') x,y = np.loadtxt('exampleFile.txt',unpack=True,delimiter=',') plt.plot() plt.title('Epic Chart') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show() Python 3 Programming Tutorial - ftplib FTP transfers Python https://www.youtube.com/watch?v=QVyAeM12wVY&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=54 from ftplib import FTP ftp = FTP('domainname.com') ftp.login(user='usernamae', passwd='password') ftp.cwd('/specificdomain-or-location/') #cwd means change working directory def grabFile(): filename = 'fileName.txt' localfile = open(filename,'wb') ftp.retrbinary('RETR '+filename, localfile.write, 1024) ftp.quit() localfile.close() def placeFile(): filename = 'fileName.txt' ftp.storbinary('STOR '+filename, open(filename, 'rb')) ftp.quit() Python 3 Programming Tutorial - Sockets intro https://www.youtube.com/watch?v=wzrGwor2veQ&index=55&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print(s) server='pythonprogramming.net' port=80 server_ip = socket.gethostbyname(server) print(server_ip) request="GET / HTTP/1.1\nHost: "+server+"\n\n" s.connect((server,port)) s.send(request.encode()) result = s.recv(4096) #print(result) while(len(result)>0): print(result) result = s.recv(1024) Python 3 Programming Tutorial - Sockets simple port scanner import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) server='pythonprogramming.net' def pscan(port): try: s.connect((server,port)) return True except: return False for x in range(1,26): #rang(1,26) means 1~25 if pscan(x): print('Port',x,'is open') else: print('Port',x,'is closed') Python 3 Programming Tutorial - Threaded port scanner https://www.youtube.com/watch?v=icE6PR19C0Y&index=57&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M import socket import threading from queue import Queue print_lock = threading.Lock() target = 'pythonprogramming.net' def portscan(port): s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: con = s.connect((target,port)) with print_lock: print('port',port,'is open!') con.close() except: pass def threader(): while True: worker = q.get() portscan(worker) q.task_done() q = Queue() for x in range(30): t = threading.Thread(target=threader) t.daemon = True t.start() for worker in range(1,101): q.put(worker) q.join() Python 3 Programming Tutorial - Sockets Binding and listening, Python 3 Programming Tutorial - Sockets: client server system https://www.youtube.com/watch?v=Q1a12QFq3os&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=58 命令: telnet localhost 5555, 若是出現錯誤'telnet' is not recognized as an internal or external command, 解決方法: Control Panel > Programs > Turn Windows features on or off 勾選 Telnet Client. import socket import sys from _thread import * host='' port=5555 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.bind((host,port)) except socket.error as e: print(str(e)) s.listen(5) def threaded_client(conn): conn.send(str.encode('Welcome, type your info\n')) while True: data=conn.recv(2048) reply='Server output: '+data.decode('utf-8') if not data: break conn.sendall(str.encode(reply)) conn.close() while True: conn,addr=s.accept() print('connected to: '+addr[0]+':'+str(addr[1])) start_new_thread(threaded_client,(conn,)) Python 2to3 - Convert your Python 2 to Python 3 automatically! https://www.youtube.com/watch?v=8qxKYnAsNuU&index=60&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M cmd窗口輸入命令: C:\Users\H\Desktop\2to3me>python C:/Python34/Tools/scripts/2to3.py -w python2ugliness.py Python Pickle Module for saving objects (serialization) https://www.youtube.com/watch?v=2Tw39kZIbhs&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=61 import pickle example_dict = {1:"6",2:"2",3:"f"} #序列化 pickle_out = open("dict.pickle","wb") #wb means write byte pickle.dump(example_dict, pickle_out) pickle_out.close() #反序列化 pickle_in = open("dict.pickle","rb") #rb means read byte example_dict = pickle.load(pickle_in) print(example_dict) print(example_dict[2]) Python Eval programming tutorial https://www.youtube.com/watch?v=1NJpqi5pqoU&index=62&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M list_str = "[5,6,7,8,9]" list_str = eval(list_str) print(list_str) print(list_str[2]) x = input("code: ") check_this_out = eval(input("code")) print(check_this_out) Exec - Python programming tutorial https://www.youtube.com/watch?v=ILPtmMAv7RM&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&index=63 exec("print('so this works like eval')") list_str = "[5,6,7,8,6]" list_str = exec(list_str) print(list_str2) exec("def test(): print('o sniiii snap!!!')") test() exec(""" def test2(): print('lets see if multi line works...') """) test2() Creating a database, table, and inserting - SQLite3 with Python 3 part 1 https://www.youtube.com/watch?v=o-vsdfCBpsU&index=64&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M import sqlite3 import time import datetime import random import matplotlib.pyplot as plt #打開https://pythonprogramming.net搜索matplotlib import matplotlib.dates as mdates from matplotlib import style style.use('fivethirtyeight') conn = sqlite3.connect('tutorial.db') c = conn.cursor() def create_table(): c.execute('create table if not exists stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)') def data_entry(): c.execute("insert into stuffToPlot values(123213,'2016-01-01','Python',5)") conn.commit() c.close() conn.close() def dynamic_data_entry(): unix = time.time() date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S')) keyword = 'Python' value = random.randrange(0,10) c.execute("insert into stuffToPlot(unix,datestamp,keyword,value) values(?,?,?,?)",(unix,date,keyword,value)) conn.commit() def read_from_db(): c.execute('select * from stuffToPlot') #data = c.fetchall() #print(data) for row in c.fetchall(): print(row) def graph_data(): c.execute('select unix, value from stuffToPlot') dates = [] values = [] from row in c.fetchall(): dates.append(datetime.datetime.fromtimestamp(row[0])) values.append(row[1]) plt.plot_date(dates,values,'-') plt.show() def del_and_update(): c.execute('select * from stuffToPlot') [print(row) for row in c.fetchall()] c.execute('update stuffToPlot set value=99 where value = 8') #修改 conn.commit() c.execute('delete from stuffToPlot where value = 99') #刪除 conn.commit() print(50*'#') #create_table() #data_entry() #for i in range(10): # dynamic_data_entry() # time.sleep(1) #read_from_db() #graph_data() del_and_update() c.close() conn.close() -----------------------------------------------------------------------------------------------------------------------------------------