YongWook's Notes

<파이썬> 기초 구문 및 잡다한 특징 본문

-software/python

<파이썬> 기초 구문 및 잡다한 특징

글로벌한량 2016. 4. 16. 16:20

2016년 1학기 (재)수강중인 컴퓨터 시스템 입문 수업에서 다루는 python언어에서 발견한 나에게 생소한 특징과 유용한 함수들을 정리해보려고한다. 개인적인 용도로 저장하는 차원에서 글로 남겼지만 새로 파이썬을 공부하시는 다른 분들에게도 참고가 될 수 있을 것 같아 포스팅한다. 툴은 pyscript를 사용한다.

  1. C, C++, Java와는 다르게 문장 마지막에 세미콜론이 없다. 
  2. 주석처리는 #을 사용한다.
  3. if, else 등의 구문 사용시 콜론을 사용한다. else if는 elif로 쓴다.
    -조건문 예제1
    if(age>35):
    	print "You are the young"
     else:
    	print "You are just a baby"
    
    -조건문 예제2
    #BMI=weight/(height**2)
    weight=input("input your weight")
    height=input("input your height in meter")
    
    #normal : 18.5<BMI<24.9
    myBMI = weight/(height**2)
    
    print "Your BMI is ",myBMI
    if(18.5<myBMI and myBMI<24.9):
        print "you are normal"
    else:
        print "you are abnormal"
        if(myBMI<18.5):
            print "you need to get more weight"
        else:
            print "you need to lose more weight"
    

  4. list에서 마지막 원소를 가져오고 싶을 때 -1을 index로 쓸 수 있다. 마지막에서 두번째는 -2.
    monthly_pay = [30,40,20,10,0,100]
    monthly_pay[0]
    # >>30
    monthly_pay[-1]
    # >>100
    
  5. 각 변수의 타입은 자동 지정되며 특정 변수의 타입을 알고 싶을 때에는 type(변수) 함수를 사용하면 된다.
    var1 = "python"
    print type(var1)
    # >> <type 'str'> 
    
    var2 = 123
    print type(var2)
    # >> <type 'int'> 
    
  6. range함수를 이용하면 범위값 이용이 편리하다.
    var1 = range(3, 7)
    print var1
    # [3, 4, 5, 6] 
    
    var2 = range(100,201,17)  #100에서 201까지 17간격의 수
    print type(var2)
    # [100, 117, 134, 151, 168, 185] 
    
  7. string의 사전식배 순서는 단순히 비교 operator를 사용하면 된다.
    str1 = 'apple'
    str2 = 'orange'
    
    if str1 < str2 :
       print str1
    else :
       print str2
    >>apple
    
  8. 파일에서 가져온 한 line 전체, 혹은 하나의 string을 대문자, 소문자로 변경하는 함수
    str = 'There is NO problem here'
    
    print str.upper()
    >> THERE IS NO PROBLEM HERE
    
    print str.lower()
    >> there is no problem here
    
    print str.capitalize() //맨 앞글자만 대문자로 변경한다.
    >> There is no problem here 
    
  9. Key와 Value로 구성된 Dictionary -http://man-about-town.tistory.com/29
    dict = {}
    dict["인공"] = "지능"
    dict["apple"] = "pie"
    dict["girl"] = "friend"
    
    for key in dict.keys():
        print dict[key]
    
    >>지능
    >>pie
    >>friend 
    
  10. String을 선언할 때는 작은따옴표와 큰 따옴표의 구분을 두지 않는다.
    str1 = 'my_mind'
    print str1
    >> my_mind
    
    str2 = "my_heart"
    print str2
    >> my_heart
    




Comments