본문 바로가기
반응형

전체 글284

[Python] 예외처리 def trys(x,y): try: x / y if y == 100: raise ValueError #강제로 예외 발생 elif y == 99: raise NameError #except에 명시적으로 정의되지 않은 예외 발생 except ZeroDivisionError: #처리할 예외 타입 지정 print "ZeroDivisionError Occurred" except TypeError as e: #예외 내용을 e에 저장 print "TypeError Occurred : %s" % e except (IndentationError,ValueError): #처리할 예외를 다수 지정 print "IndentationError or ValueError Occurred" except: #기본 예외 처리 print.. 2016. 3. 8.
[Python] 생성기 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 r=1g=gene(6) while r 2016. 3. 8.
[Python] 파일 입출력 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, 2016. 3. 2.
[Python] 함수 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__ 2016. 3. 2.
[Python] 튜플 (생성 후 데이터 추가/변경/삭제 불가) tuple1 = ("123","456",789,"data") item1,item2,item3,item4 = tuple1 #차례대로 데이터 대입 tuple2 = ( ) #빈 튜플 생성tuple3 = ("123",) #1개 요소 튜플 생성tuple4 = "123", #1개 요소 튜플 생성 2016. 3. 2.
[Python] 집합 (데이터 순서 없음, 중복값 없음) 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 #대칭차집합 (교집합 반대) 2016. 3. 2.
반응형

바로가기