Catalog
install
Basic use
while and for loops
if judgement
Defining function
Variable form
Module installation
File read
Class class
Input input
Tuple, list, dictionary
Modular
Others (completed)
- continue & break
- try error handling
- zip lambda map
- Copy & deep copy
- threading what is multithreading
- Multiprocessing what is multiprocessing
- What is a tkinter window
- pickle save data
- set find difference
- regular expression
The following is written while writing. It's a bit messy. It can be used as a reference.
#t1.py import collections import threading import time import copy from queue import Queue import multiprocessing as mp import threading as td class Calculator: name='xyb' def __init__(self,name,num1=1,num2=1): self.name=name self.n1=num1 self.n2=num2 def cal(self): return self.n1+self.n2 class Fib(object): def __init__(self,max): self.max=max self.n,self.a,self.b=0,0,1 def __iter__(self): return self def __next__(self): if self.n<self.max: r=self.b self.a,self.b=self.b,self.a+self.b self.n=self.n+1 return r raise StopIteration() def test(): #tup=('python',3.6,64) #for i in tup: # print(i) #dic={} #dic['name']='xyb' #dic['birth']='0901' #dic['sex']='male' #for key in dic: # print(key,dic[key]) #s=set(['python','python2','psython3','python']) #for item in s: # print(item) #using Fib object for i in Fib(5): print(i) def fib(max): a,b=0,1 while max: r=b a,b=b,a+b max-=1 yield r def calscore(name,*grades): total_score=0 for grade in grades: total_score+=grade print(name,total_score) def insertinfor(name,**infor): print(name) for k,v in infor.items(): print(k,v) name='xyb' def change(): global name name='xyb2' def func(): return 22 def thread_job(): print('this is a thread of %s'%threading.current_thread()) def main(): thread=threading.Thread(target=thread_job)#Defining threads thread.start()#Let threads start working #if __name__=='__main__': #print('past:',name) #change() #print('now:',name) #if 4<5: # test() #elif 4>8: # print('hehe') #else: # for i in fib(5): # print(i) #calscore('xyb',66,71,44,81,99) #insertinfor('xyb',age=23,sex='male',country='china') #text="\tthis is my first test\n\tplease wait for me\n" #my_file=open('firstfile.txt','w') #my_file.write(text) #my_file.close() #Cal=Calculator('xyb',1,2) #print(Cal.cal()) #score=int(input('Please input your score:\n')) #if score>=90: # print('great grade!\n') #elif score>=80: # print('good grade!\n') '''while True: n,m,g=map(int,input().split()) pro={} for i in range(0,m): pro[i]=int(input()) stu={} for i in range(0,n): stu[0]''' #a_tuple=(12,3,5,15,6) #another_tuple=12,3,5,15,6 #a_list=[12,3,67,7,82] #for content in a_tuple: # print(content) #for content in a_list: # print(content) '''a_list.append(15) a_list.insert(1,22) #for content in a_list: # print(content) a_list.remove(3) for content in a_list: print(content) print(a_list[-1]) print(a_list[-3:]) print(a_list.index(15)) print(a_list.count(15)) a_list.sort() print(a_list) a_list.sort(reverse=True) print(a_list)''' #n = int(input()) #line = [[0] * n] * n #for i in range(n): # line[i] = input().split(' ') #print(line) #d={'apple':[1,2,3],'pear':{1:3,3:'a'},'orange':func} #print(d['apple']) #print(d['pear'][3]) #print(d['orange']) '''try: file=open('secondfile.txt','r') except Exception as e: print(e) response=input('do you want to create a new file?(y/n)') if response=='y': file=open('secondfile.txt','w') file.write('secondfile content...') file.close() else: pass''' '''a=[1,2,3] b=[4,5,6] ab=zip(a,b) print(list(ab))#list visualization required for i,j in zip(a,b): print(i/2,j*2) fun=lambda x,y:x+y#Simplified function x=int(input('x=')) y=int(input('y=')) print(fun(x,y)) print(list(map(fun,[1],[2])))#map binds functions and parameters together print(list(map(fun,[1,2],[3,4]))) def fun(x,y): return x+y''' #main() '''def t1_job(): print("t1 start") for i in range(10): time.sleep(0.1)#Task interval 0.1s print("t1 finish") def t2_job(): print("t2 start") print("t2 finish") if __name__=='__main__': thread1=threading.Thread(target=t1_job,name='T1') thread2=threading.Thread(target=t2_job,name='T2') thread1.start() thread2.start() thread2.join() thread1.join() print("all done")''' '''def job(l,q): for i in range(len(l)): l[i]=l[i]**2 q.put(l) def multithreading(): q=Queue() threads=[] data=[[1,2,3],[3,4,5],[4,4,4],[5,5,5]] for i in range(4): t=threading.Thread(target=job,args=(data[i],q)) t.start() threads.append(t) for thread in threads: thread.join() results=[] while q.empty()==False: results.append(q.get()) print(results) if __name__=='__main__': multithreading()''' '''def job(l,q): res=sum(l) q.put(res) def multithreading(l): q=Queue() threads=[] for i in range(4): t=threading.Thread(target=job,args=(copy.copy(l),q),name='T%i'%i) t.start() threads.append(t) for t in threads: t.join() total=0 while q.empty()==False: total+=q.get() print(total) def normal(l): total=sum(l) print(total) if __name__=='__main__': l=list(range(1000000)) s_t=time.time() normal(l*4) print('normal:',time.time()-s_t) s_t=time.time() multithreading(l) print('multithreading:',time.time()-s_t) def job1(): global A,lock lock.acquire() for i in range(10): A+=1 print('job1',A) lock.release() def job2(): global A,lock lock.acquire() for i in range(10): A+=10 print('job2',A) lock.release() if __name__=='__main__': lock=threading.Lock() A=0 t1=threading.Thread(target=job1) t2=threading.Thread(target=job2) t1.start() t2.start() t1.join() t2.join() def job(a,d): print(a+d) if __name__=='__main__': p1=mp.Process(target=job,args=(1,2)) p1.start() p1.join() def job(q): res=0 for i in range(1000): res+=i+i**2+i**3 q.put(res) if __name__=='__main__': q=mp.Queue() p1=mp.Process(target=job,args=(q,)) p2=mp.Process(target=job,args=(q,)) p1.start() p2.start() p1.join() p2.join() res1=q.get() res2=q.get() print(res1+res2) def job(q): res=0 for i in range(1000000): res+=i+i**2+i**3 q.put(res) def multicore(): q=mp.Queue() t1=mp.Process(target=job,args=(q,)) t2=mp.Process(target=job,args=(q,)) t1.start() t2.start() t1.join() t2.join() res1=q.get() res2=q.get() print('multicore:',res1+res2) def multithread(): q = mp.Queue() t1 = td.Thread(target=job, args=(q,)) t2 = td.Thread(target=job, args=(q,)) t1.start() t2.start() t1.join() t2.join() res1 = q.get() res2 = q.get() print('multithread:', res1 + res2) def normal(): res=0 for _ in range(2): for j in range(1000000): res+=j+j**2+j**3 print('normal:',res) if __name__=='__main__': st=time.time() normal() st1=time.time() print('normal time:',st1-st) multithread() st2=time.time() print('thread time:',st2-st1) multicore() st3=time.time() print('process time:',st3-st2) def job(x): return x*x def multicore():#Multi process pool=mp.Pool(processes=3)#The process pool method defines the number of CPU cores as 3 res=pool.map(job,range(10)) print('map:',res) res=pool.apply_async(job,(2,))#How to apply #Get results with get print(res.get()) #Iterator to input multiple parameters multi_res=[pool.apply_async(job,(i,)) for i in range(10)] #Remove from iterator print('apply_async:',[res.get() for res in multi_res]) if __name__=='__main__': multicore()''' def job(v,num,l): l.acquire()#Lock up for _ in range(5): time.sleep(0.1) v.value+=num print(v.value) l.release()#release def multicore(): l=mp.Lock() v=mp.Value('i',0)#Define shared variables p1=mp.Process(target=job,args=(v,1,l)) p2=mp.Process(target=job,args=(v,3,l)) p1.start() p2.start() p1.join() p2.join() if __name__=='__main__': multicore() #balance.py d=float(input('Please enter what is your initial balance: \n')) p=float(input('Please input what is the interest rate (as a number): \n')) d=float(d+d*(p/100)) year=1 while year<=5: d=float(d+d*p/100) print('Your new balance after year:',year,'is',d) year=year+1 print('your final year is',d)