#!/usr/bin/env python # coding: utf-8 # *** # *** # # 3. 내장 자료형의 기초 # *** # *** # *** # ## 1 수치 자료형 # *** # ### 1-1 정수형 상수 # In[1]: a = 23 # 10진 정수 b = 023 # 8진 정수 c = 0x23 # 16진 정수 print type(a), type(b), type(c) print a, b, c # In[1]: import sys print sys.maxint # 최대 정수 값 확인 # ### 1-2 실수형 상수 # In[2]: a = 1.2 b = 3.5e3 c = -0.2e-4 print type(a), type(b), type(c) print a, b, c # ### 1-3 롱형 상수 # - 메모리가 허용하는 한 유효자리수는 무한대 # In[2]: h1 = 123456789012345678901234567890L # 마지막에 L을 붙여서 명시적으로 long 형이라고 알려도 되고 print type(h1) print h1 * h1 print h2 = 123456789012345678901234567890 # L을 붙이지 않아도 int형이 담을 수 있는 수치를 초과하면 자동으로 long형이 된다. print type(h2) print h2 * h2 print h3 = 123L print type(h3) print h4 = 123 print type(h4) # In[15]: 123456789012345678890 # 자동 long형 변환 # ### 1-4 복소수형 상수 # In[3]: a = 10 + 20j print a b = 10 + 5j print a + b # ### 1-5 수치 자료형의 치환 # - 아래 예에서는 x가 지니고 있는 1의 값이 변경되는 것이 아니라 새로운 객체 2로 레퍼런스를 변경하는 것임 # In[18]: x = 1 x = 2 # ![image1](images/referenceChangeNumerical.png) # ### 1-6 수치 연산과 관련된 내장 함수 # In[105]: print abs(-3) print int(3.141592) print int(-3.1415) print long(3) print float(5) print complex(3.4, 5) print complex(6) # In[1]: print divmod(5, 2) print print pow(2, 3) print pow(2.3, 3.5) # ### 1-7 math 모듈의 수치 연산 함수 # In[109]: import math print math.pi print math.e print math.sin(1.0) # 1.0 라디안에 대한 사인 값 print math.sqrt(2) # 제곱근 # In[111]: r = 5.0 # 반지름 a = math.pi * r * r # 면적 degree = 60.0 rad = math.pi * degree / 180.0 # 각도를 라디안으로 변환 print math.sin(rad), math.cos(rad), math.tan(rad) #sin, cos, tan # *** # ## 2 문자열 # *** # ### 2-1 문자열 형식 # - 한 줄 문자열 형식 # - 단일 따옴표 # - 이중 따옴표 # In[81]: print 'Hello World!' print "Hello World!" # - 여러 줄 문자열 형식 # - 연속된 단일 따옴표 세 개 # - 연속된 이중 따옴표 세 개 # In[1]: multiline = ''' To be, or not to be that is the question ''' print multiline multiline2 = """ To be, or not to be that is the question """ print multiline2 # ### 2-2 인덱싱(Indexing)과 슬라이싱(Slicing) # - Indexing # In[82]: s = "Hello world!" print s[0] print s[1] print s[-1] print s[-2] # - Slicing # - 형식: [start(included) : stop(excluded) : step] # - 기본값: start - 0, stop - 자료형의 크기, step - 1 # In[83]: s = "Hello world!" print s[1:3] print s[0:5] # In[85]: s = 'Hello' print s[1:] print s[:3] print s[:] # In[86]: s = 'abcd' print s[::2] print s[::-1] # - 문자열 자료형은 변경되지 않는다. # In[88]: s = 'Hello World' s[0] = 'h' # - 문자열을 변경하려면 Slicing 및 연결 연산 (+)을 주로 이용한다. # In[9]: s = 'Hello World' s = 'h' + s[1:] s # ### 2-3 문자열 연산 # - +: 연결 # - *: 반복 # In[87]: print 'Hello' + '' + 'World' print 'Hello' * 3 print '-' * 60 # ### 2-4 문자열의 길이 # - len(): 문자열의 길이를 반환하는 내장함수 # In[90]: s = 'Hello World' len(s) # ### 2-5 문자열내 포함 관계 여부 # - in, not in: 문자열내에 일부 문자열이 포함되어 있는지를 파악하는 키워드 # In[92]: s = 'Hello World' print 'World' in s print 'World' not in s #

참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일