[Python] 코루틴
def cor(txt): print “coroutine start” while True: line = (yield) #send로 전달받은 값을 line에 저장 if txt in line: print line c=cor(“py”) #코루틴 초기화 c.next() #코루틴 실행 c.send(“show me the money”) #코루틴에 값 전달 c.send(“snoopy”) c.send(“black … Read more
def cor(txt): print “coroutine start” while True: line = (yield) #send로 전달받은 값을 line에 저장 if txt in line: print line c=cor(“py”) #코루틴 초기화 c.next() #코루틴 실행 c.send(“show me the money”) #코루틴에 값 전달 c.send(“snoopy”) c.send(“black … Read more
def trys(x,y): try: x / y if y == 100: raise ValueError #강제로 예외 발생 elif y == 99: raise NameError #except에 명시적으로 정의되지 않은 … Read more
def gene(n): print “Generator start” while n < 10: yield n #현재 n 값을 반환, 생성기 자체는 종료되지 않고 멈춰있음 n += 1 print “Generator end” for i in gene(1): #순차적으로 생성기 호출 (next) print i ... Read more
f=open(“C:\Windows\System32\drivers\etc\hosts”) #파일 객체 생성 f2=open(“out.log”,”w”) line=f.readline() #파일 read while line: print line, # ,는 줄바꿈 생략 #print(line,end=”) #파이썬3 print >>f2,line # f2에 line 내용 출력 #print(line,file=f2) #파이썬3 line=f.readline() f.close() for line2 in open(“C:\Windows\System32\drivers\etc\hosts_tmp”): print line2,
count=0 def func(a,b=1): #두번째 인수에 기본값 설정 “func() is tutorial function” #함수 문서화 문자열 global count #전역 변수를 함수 내에서 사용 count += 1 print “call count : %d” % count print a,”+”,b return a+b print func(4,5) print func(9) print func.__doc__
tuple1 = (“123″,”456″,789,”data”) item1,item2,item3,item4 = tuple1 #차례대로 데이터 대입 tuple2 = ( ) #빈 튜플 생성 tuple3 = (“123”,) #1개 요소 튜플 생성 tuple4 = “123”, #1개 요소 튜플 생성
set1 = set([1,2,3,4]) set2 = set(“hello”) #중복값은 제거됨 (helo) set1.add(5) #값 1개 추가 set1.update([6,7,8]) #값 여러개 추가 set2.remove(‘e’) #값 제거 set1 | set2 #합집합 set1 & set2 #교집합 set1 – set2 #차집합 set1 ^ set2 #대칭차집합 (교집합 반대)
dic1 = {“item1” : “123”, “item2” : 456, “item3” : “data”} dic2 = {} #빈 사전 생성 dic3 = dict() #빈 사전 생성 dic1[“item4”] = “data2” #키 추가 del dic1[“item3”] #키 삭제 if “item2” in dic1: #사전에 해당 키가 있는지 확인 i=dic1[“item2”] else: i=0 j=dic1.get(“item2”,0) … Read more
list1 = [“123″,”456″,”abc”] list1[0] #색인은 0부터 (0~2) list1.append(“new data”) #새 항목 추가 list1.insert(1,”ins”) #idx 1위치에 항목 추가 list1[1:2] #idx 1부터 idx 2 이전까지 (idx 1만 출력) list1[1:] #idx 1부터 끝까지 list2=[] #빈 리스트 생성 list3=list() #빈 리스트 생성
data1 = range(1,10) #1~9의 값을 가지는 리스트 생성 data2 = 0 for i in data1: print i while data2 < 10: data2+=1 if data2 % 2: print data2, #홀수면 출력 else: continue #짝수면 아래 구문 무시하고 반복문 ... Read more