아주 가끔씩 급하게 프로그래밍 할때가 생긴다.
평소 같으면 비베나 에디트 플러스로 자바로 코딩할테지만 인터프리터를 사용하면 금새 확인할 수가 있다.

일단 파이썬을 사용한다면 기본 신텍스를 까먹지 않아야 하지만.. 자바나 VC++를 주로 사용하므로 곧잘 까먹기 때문에 문법을 익히자.

1. 자료형과 연산자

type
내용
리스트
 L1=[]
 L2=[0,1,2]
 L3=['spam','eggs',['def','pam']]
 L2[i],   L3[i][j]
 len(L2)      : 원소의 개수
 L2+L3
 L2.append(4)
 L2.sort()
 L2.index(1) : 검색
 L2.reverse()
 del L2[i]   : 삭제
사전
 d1={}
 d2={'spam' : 2, 'eggs' : 3}
 d3={'food' : {'ham' : 1}}
 d2['eggs']
 d3['food']['ham']
 d2.has_key('eggs') :key를 가지는지
 d2.keys()          :key 리스트
 len(d2)
파일
 outfile=open('spam.txt', 'w')
 infile=open('data.txt','r')
 S=infile.read()     :파일을 한 문자열로
 S=infile.read(N)           :N개만 읽기
 S=infile.readilne()           :한줄 읽기
 L=infile.readilnes()   :한 줄을 리스트로
 outfile.write(S)       :파일에 S를 쓰기
 outfile.writelines(L)     :리스트를 쓰기
 outfile.close()

2. 기본문

2-1 if 문의 사용
 x = 'killer rabbit'
 if x == 'roger' :
        print "x is roger"
 elif x == 'bugs' :
        print "x is bugs"
 else :
        print "run run"

2-2 switch의 사용
 choice = 'ham'
 print {'spam' : 1.24, 'ham' : 1.99, 'eggs' : 0.99, 'bacon' : 1.1}  [choice]  ------> 1.99

2-3 while의 사용
 x = y/2
 while x>1 :
        if y % x == 0 :
                print y , 'has factor', x
                break
        x = x-1
 else:
        print y, 'is prime'

2-4 for의 사용
 items = ['aaa', 111, (4,5), 2.01]
 tests = [(4,5), 3.14]
 for key in tests:
        for item in items:
                if item == key:
                        print key, "was found"
                        break
        else:
                print key, "was not found"

3. 함수
 def intersect(*args) :
        res = []
        for x in args[0] :
                for other in args[1:] :         
                        if x not in other : break
                else :
                        res.append(x)
        return res
 def union(*args):
        res = []
        for seq in args:
                for x in seq:
                        if not x in res:
                                res.append(x)
        return res

4. class 사용하기
4-1 class 사용 예제
class FirstClass:
        def __init__(self, value):
                self.data=value
        def setdata(self, value):
                self.data=value
        
        def display(self):
                print self.data
 x = FirstClass()
 (또는 x = FirstClass("King") 도 가능)
 y = FirstClass()
 x.setdata("King")
 y.setdata(3.141592)
 x.display()
 y.display()
 x.data = 'New Data'
 x.display()

4-2 class의 상속 이용하기(상속받고자 하는 class를 괄호를 사용하여 적어준다)

 class SecondClass(FirstClass):
        def display(self):
                print 'value = %s'  % self.data 
 z = SecondClass()
 z.setdata(42)   :상속 받았음
 z.display()     :오버라이딩 됨
 --> value = 42
4-3 class의 생성 시 다음과 같은 방법이 가능하다
 for klass in FirstClass, SecondClass, ThirdClass        
        object = klass(klass.__name__)
        object.display()
 -->  FirstClass
        SecondClass
        ThirdClass




  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기