python datatype
TRANSCRIPT
StudyOf Landvibe
Python - DataType
Outline
1. Overview2. Built-in Type3. Data Type4. Input / Output5. Mutable vs Immutable6. Data Structure
Calling a function
Object instantiation
Overview - Exampleimport math def showArea(shape): print("Area = ", shape.area() )
def widthOfSquare(area): return math.sqrt(area) class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height ###### Main Program ######r = Rectangle(10, 20) showArea(r)
Import a library module
Function
No Semicolon ; No brackets {}
Class
Comment
Indent ( 보통 4칸 )
Overview – Similarities to Java
• Everything inherits from “object”• Large standard library• Garbage collection
Overview – Differences to Java
• Dynamic Typing• Everything is “object”
• No name declartions• Sparse syntax
• No {} for blocks, just indentation• No () for if/while conditions
• Interative interpreter• # for comments
Overview – Python Interpreter
Complier 가 python code 를 컴파일해서 .pyc file(byte code, intermediate code) 로 변환시킨다
.py file(python code)
Compiler .pyc file Inter-preter Output
Interpreter가 .pyc file 을 프로세스에 load하여 실행시킨다
Overview – Python Interpreter
엥 ? 이거 자바 아니에요 ????
자바는 컴파일러 언어라면서요 !?!?!?!?!!?
Overview – Python Interpreter
Complier 가 python code 를 컴파일해서 .pyc file(byte code, intermediate code) 로 변환시킨다
.py file(python code)
Compiler .pyc file Inter-preter Output
Python Interpreter 쓰면 CPythonJVM 쓰면 JythonCLR 쓰면 Ironpython
Interpreter = VM( 거의 같습니다 )
Compile 과정은 High Level Language 의 공통적인 특징입니다 .
Built-in Type Hierarchy
Data Type – Preview
• 파이썬에서는 모든 것이 객체입니다 .
123a>>> a=123
>>> print(a)123
Data Type – Preview
• 변수 이름에 사용할 수 있는 문자• 소문자 (a~z)• 대문자 (A~Z)• 숫자 (0~9)• 언더스코어 (_)
가능• bominkyo13 • __landvibe• KoenHee_91
불가능• 13je_jang• landvibe!@#• if
Data Type – Preview
• 예약어는 변수이름으로 사용불가
Data Type
• 데이터의 공통된 특징과 용도에 따라 분류하여 정의한 것• 숫자형 (Numeric Type)
- Integer, float, complex• 논리형 (Boolean Type)
- True, False• 문자열형 (String Type)
- “This is String”
Numeric Types• Integers
• Generally signed, 32-bit• Long Integer
• Unlimited size ( 동적으로 결정 , 64 비트 이상 가능 )• In python3, long = int
• Float• 부동소수점• Python 에는 double 형 없음
• Complex• Format : <real> + <imag>j• Example : 6+3j
Numeric Types
>>> 456456>>> 00숫자 앞에 기호가 없으면 양수 , + 붙히면 양수 , - 붙히면 음수>>> 123123>>> +123123>>> -123-123
연속된 숫자는 리터럴 정수로 간주
Numeric Types
>>> 5+1015>>> 5-10-5/ 연산은 부동소숫점 , // 연산은 몫 , % 연산은 나머지 값 >>> 5/100.5>>> 5//100>>> 5%105
덧셈 , 뺄셈 , 곱셈 , 나눗셈 가능 , ** 는 n 제곱>>> 5*1050>>> 5/100.5
>>> 5/0Taceback (most recent call lask): File “<stdin>”, line 1, in <mod-ule>ZeroDivisionError: division by zero
0 으로 나누지 맙시다
>>> 2**101024
Numeric Types
• 연산 우선 순위• 2400 // 500 * 500 + 2400 % 500 ?
• 진수 (base)• Default : 10 진수 (Decimal)• 2 진수 (Binary) : 0b, 0B• 8 진수 (Octal) : 0o, 0O• 16 진수 (Hex) : 0x, 0X• 10 진수 > n 진수 변환 : bin(), oct(), hex() 함수 사용
• 형 변환• int(), float() 함수 사용
Numeric Types
>>> 2400 // 500 * 500 + 2400 % 5002400>>> ((2400 // 500) * 500) + (2400 % 500)2400진수 변환>>> 0b102>>> 0o108>>> 0x1016
연산자 우선 순위
>>> bin(10)‘0b1010’>>> oct(10)‘0o12’>>> hex(10)‘0xa’ // str 형으로 반환
Numeric Types
>>> int(True)1>>> int(False)0
형 변환 (int)
>>> int(99.5)99>>> int(1.0e4)10000
>>> int(’88’)88>>> int(‘-23’)-23
>>> int(’99.5’)ERROR>>> int(‘1.0E4’)ERROR
소수점 , 지수를 포함한 문자열은 처리 x
>>> 4+0.94.9
숫자의 타입을 섞어서 사용하면 , 자동으로 형변환
Numeric Types
>>> float(True)1.0>>> float(False)0.0
형 변환 (float)
>>> float(99)99.0>>> float(1.0e4)10000.0
>>> float(’88’)88.0>>> float(‘-23’)-23.0
Numeric Types
• 정리연산 기호 결과 우선순위x + y x 더하기 yx - y x 빼기 yx * y x 곱하기 yx / y x 나누기 y (float 값 )x // y x 를 y 로 나눈 값의 몫x % y x 를 y 로 나눈 값의 나머지-x 부호 변경+x 변동 없음x ** y x 의 y 제곱
낮음
높음
Boolean Types
비교 연산자 뜻 < 작은 <= 작거나 같은 > 큰 >= 크거나 같은 == 같은 != 같지 않은 is 같은 객체인 is not 같은 객체가 아닌
논리 연산자 결 과 x or y x, y 중 하나만
참이면 참 , 나머지는 거짓
x and y x, y 모두 참이면 참 , 나머지는 거짓
not x x 가 참이면 거짓 ,x 가 거짓이면 참
• True & False
Boolean Types
>>> a=123123>>> b=123123>>> id(a)25428720>>> id(b)25428704>>> a is b # is 는 id 값을 비교False>>> a == b # == 는 내용을 비교True
== vs is
Boolean Types
>>> 4 > 9 or 3 > 2True>>> 4 > 9 and 3 > 2False>>> not 4 > 9True
간단한 예제 !
String Types
• 파이썬의 가장 큰 장점 중 하나 – 문자열 처리가 쉽다• 문자열 처리는 활용도가 아주 높음 !• Sequence( 배열의 성질 ) 의 Immutable 한 Type• 문자열은 인용 부호를 사용하여 만들 수 있다
• ‘Single Quotes’• “Double Quotes”• “”” Triple Quotes””” or ‘’’ Triple Quotes’’’
• 예시>>> print(‘This string may contain a “ ’)This string may contain a “>>> print(“A ‘ is allowed”)A ‘ is allowed
String Types
>>> str(98.6)‘98.6’>>> str(1.0e4)‘10000.0’>>> str(True)‘True’
데이터 타입 변환 str()
>>> ‘Inha’ + ‘Univ’‘InhaUniv’
결합 : str1 + str2
>>> ‘Inha’ * 5‘InhaInhaInhaInhaInha’
반복 : str * number
String Types
>>> pirnt(“ 허 xx 중간고사 점수 :“ + 30)
str() 을 쓰는 이유 ?
>>> pirnt(“ 허 xx 중간고사 점수 :“ + str(30))
명시적으로 형변환이 필요할 때 !
String Types
>>> letter = ‘landvibe’>>> letter[0]‘l’>>> letter[1]‘a’>>> letter[7]‘e’>>> letter[0:3]‘lan’>>> letter[1:4]‘and’>>> letter[3:]‘dvibe’>>> letter[:]‘landvibe’
문자열 추출 : str[] > Seqeunce 이기 때문에 배열처럼 사용 가능 !
String Types
>>> print(“”” 보민아공부좀하자“”” )
보민아공부좀하자
“”” “”” 은 어따 쓰지 ?
>>> s=“ 보민아 공부좀 하자”>>> len(s)10
문자열의 길이 : len()
>>> print(‘ 보민아 \n 공부좀 \n 하자’ )보민아공부좀하자
이스케이프 문자열 : \n
String Types
>>> a=‘ 파이썬 프로그래밍 쉽네요 !’>>> a.startswith(‘ 파이썬’ ) # 문자열이 ‘파이썬‘으로 시작하는지 확인True>>> a.endswith(‘!’) # 문자열이 ‘ !’ 로 끝나는지 확인True>>> a.endswith(‘ 구려요’ ) # 문자열이 ‘구려요’로 끝나는지 확인False>>> a.replace(‘ 파이썬’ , ‘python’) # ‘ 파이썬’을 ‘ python’ 으로 변경‘python 프로그래밍 쉽네요 !>>> ‘Python’.upper() # ‘Python’ 을 대문자로 변경‘PYTHON’>>> ‘Python’.lower() # ‘Python’ 을 소문자로 변경‘python’>>> ‘z’.join(‘Python’) # ‘Python’ 사이에 ‘ z’ 문자 끼워 넣기‘Pzyztzhzozn’
그 밖의 문자열 함수들
String Types
다 외울 필요 없습니다 .
필요할 때마다 찾아쓰세요 .저도 다 몰라요
Input & Output
표준 입력 : input(‘ 질문 내용’ )
>>> deadline = input(‘ 양욱씨 통금이 몇시에요 ?’)‘ 양욱씨 통금이 몇시에요 ?’ 11 시 30 분입니다>>> deadline‘11 시 30 분입니다’input 함수의 반환값은 무조건 str 입니다 !
>>> num = input(‘ 숫자를 입력하세요’ )숫자를 입력하세요 3>>> num‘3’>>> type(num)<class ‘str’>
Input & Output
표준 출력 : print( 출력내용 , end=‘\n’)>>> print(‘’Life is good”)Life is good큰따옴표 (“) 로 둘러 싸인 문자열은 + 와 동일 , 띄어 쓰기는 콤마 (,) 로 한다>>> print(“Life” ”is” ”good”)Lifeisgood>>> print(“Life”+”is” +”good”)Lifeisgood>>> print(“Life”, ”is”, ”good”)Life is good띄어 쓰기는 콤마 (,) 로 한다>>> for i in range(10):… print(i, end=“ “)0 1 2 3 4 5 6 7 8 9
Mutable vs Immutable
Mutable : 변할 수 있는 데이터형Immutable : 변할 수 없는 데이터형 , 변할 수 없으니 새로 생성 !
>>> hello = “ 안녕하세요”>>> a = id(hello)>>> hello = “ 반값습니다”>>> a == id(hello) # 식별자가 다르다 !!False
Immutable 예제
hello 변수의 값을 변경한게 아니라메모리에 새로운 공간을 생성한다음에 그곳에 값을 복사한 것 !
Mutable vs Immutable
>>> hello_list = [‘hi’]>>> a = id(hello_list)>>> hello_list[0] = [‘hello’]>>> a == id(hello_list) # 식별자가 같음 !True
Mutable 예제
hello_list[0] 의 값을 변경
Mutable Immutable리스트형 (list)사전형 (dict)집합형 (set)바이트 배열형 (byte array)
숫자형 (numbers) : int, float, com-plex문자열형 (string)튜플형 (tuple)불편집합형 (frozenset)바이트형 (bytes)
기억해두세요 !!!!!!!!
Data Structure
• 데이터를 활용 방식에 따라 조금 더 효율적으로 이용할 수 있도록 컴퓨터에 저장하는 여러방법• 리스트형 (List Type)• 튜플형 (Tuple Type)• 세트형 (Set Type)• 사전형 (Dictionary Type)
List Type
• 하나의 집합 단위로 동일한 변수에 순차적으로 저장• 배열 (Array) 이라고 불리기도 함• [] 로 선언>>> pockets = [4, 6, 1, 9]
4 6 1 9리스트 pockets :
양수 index [0] [1] [2] [3]
음수 index [-4] [-3] [-2] [-1]
List Type
• 퀴즈 !>>> pockets = [4, 6, 1, 9]
1. pockets[0]
2. pockets[3]
3. pockets[4]
4. pockets[-1]
5. len(pockets)
6. type(pockets)
List Type
• 정답>>> pockets = [4, 6, 1, 9]
1. pockets[0] > 4
2. pockets[3] > 9
3. pockets[4] > IndexError : list index out of range
4. pockets[-1] > 9
5. len(pockets) > 4
6. type(pockets) > <class ‘list’>
List Type
• 리스트 데이터 변경>>> pockets = [4, 6, 1, 9]>>> pockets[0] = 3>>> pockets[3, 6, 1, 9]리스트 항목 추가 : append(value)
>>> pockets.append(7)>>> pockets[3, 6, 1, 9, 7]
리스트 항목 삭제 : remove(value)
>>> pockets.remove(1)>>> pockets[3, 6, 9, 7]
리스트 항목 삽입 : insert(idx, val)
>>> pockets.insert(1,2)>>> pockets[3, 2, 6, 1, 9, 7]
리스트 항목 추출 : pop(idx)
>>> pockets.pop(3)1>>> pockets[3, 2, 6, 9, 7]
List Type
• 리스트 데이터 자르기변수명 [ start : end ] - 리스트의 start 인덱스 ~ end-1 인덱스 까지 - start, end 생략 가능>>> pockets = [4, 6, 1, 9]>>> pockets[1:3][6, 1]>>> pockets[:3][4, 6, 1]>>> pockets[-2:][1, 9]>>> pockets[:][4, 6, 1 ,9]
List Type
• 리스트 데이터 복사= vs [:]
>>> pockets = [4, 6, 1, 9]>>> pockets_copy = pock-ets>>> pockets_copy[4, 6, 1, 9]퀴즈 !!
>>> pockets_copy.append(3)>>> pockets_copy[4, 6, 1, 9 ,3]>>> pockets # 결과값 ??
>>> pockets = [4, 6, 1, 9]>>> pockets_copy = pock-ets[:]>>> pockets_copy[4, 6, 1, 9]
List Type
• 리스트 데이터 복사정답 !
정리 pockets_copy = pockets 는 같은 메모리를 참조 pockets_copy = pockets[:] 는 값을 복사
>>> pockets[4, 6, 1, 9 ,3]>>> id(pockets) == id(pockets_copy)True
>>> pockets[4, 6, 1, 9]>>> id(pockets) == id(pockets_copy)False
List Type
• 리스트 데이터 합치기 & 확장하기
리스트 확장하기>>> a.extend(b)>>> a # a 뒤에 b 가 붙는다[1, 2 ,3 ,4 ,5 ,6]
>>> a = [1, 2, 3]>>> b = [4, 5, 6]>>> c = a + b # 새로 생성된다 !>>> c[1, 2, 3, 4, 5 , 6]
List Type
• 리스트 삭제del() 함수 사용>>> a = [1, 2, 3, 4, 5, 6]>>> del a[0]>>> a[2, 3, 4, 5, 6]>>> del a[1:3]>>> a[2, 5 ,6]>>> del a[:]>>> a[]>>> del a>>> aNameError: name ‘a’ is not defined
List Type
• 리스트 다양하게 사용하기리스트안에 여러개의 타입 혼용 가능>>> many_type = [‘ 건희’ , ‘je_jang’, 100, 3.14 ]
중첩 리스트 사용 가능>>> many_type = [‘ 건희’ , ‘je_jang’, 100, 3.14 ]>>> nested_list = [ [1, 2, 3, 4], many_type , [5, 6, 7, 8]>>> nested_list[1][1]‘je_jang’>>> nested_list[2][3]8
Tuple Type• Immutale 한 리스트형• 다른 종류의 데이터형을 패킹 언패킹 할 때 사용• 추가 , 삭제 , 자르기 불가능 !• () 로 생성 , but 생략 가능>>> landvibe = ‘ 민승’ , 1993, ‘ 우곤’ , 1993 # () 괄호 생략가능>>> landvibe(‘ 민승’ , 1993, ‘ 우곤’ , 1993)>>> landvibe[0] # 리스트처럼 인덱스 기능 사용 가능‘ 민승’>>> landvibe[1:3](1993, ‘ 우곤’ , 1993)
Tuple Type
>>> landvibe = (‘ 민승’ , 1994, ‘ 우곤’ , 1994)>>> landvibe(‘ 민승’ , 1994, ‘ 우곤’ , 1994)>>> landvibe[0] = ‘ 건희’TypeError: ‘tuple’ object does not support item ass-ginment
Tuple 은 Immutable 합니다 !
>>> landvibe = [‘ 민승’ , 1994], [‘ 우곤’ , 1994]>>> landvibe([‘ 민승’ , 1994], [‘ 우곤’ , 1994])>>> landvibe[1][0] = ‘ 건희’
여기서 퀴즈 !!!
결과는 !?!?!?
Tuple Type
>>> landvibe = [‘ 민승’ , 1994], [‘ 우곤’ , 1994]>>> landvibe([‘ 민승’ , 1994], [‘ 우곤’ , 1994])>>> landvibe[1][0] = ‘ 건희’>>> landvibe ([‘ 민승’ , 1994], [‘ 건희’ , 1994])
정답 !
List 는 Mutable 하기 때문에 가능합니다 !
Tuple Type
>>> empty = ()>>> empty1 = tuple()>>> type(empty)<class ‘tuple’>>>> len(empty)0>>> type(empty1)<class ‘tuple’>>>> len(empty1)0>>> single = “ 건희” , # , 에 주목하자>>> type(single)<class ‘tuple’>>>> len(single)1
빈튜플 , 하나의 항목만 있는 튜플 생성시 주의사항
Tuple Type
>>> landvibe = ‘ 민승’ , 1994, ‘ 우곤’ , 1994# 이게 패킹>>> a, b, c, d = landvibe # 이게 언패킹>>> a‘ 민승’>>>b1994
패킹 vs 언패킹
형변환 - list(), tuple() 함수 사용>>> landvibe_list= list(landvibe)>>> type(landvibe_list)<class ‘list’>>>> landvibe_tuple = tuple(landvibe_list)<class ‘tuple’>
Set Type• Mutable 한 데이터 구조• Index, 순서가 없음• 중복이 허용되지 않음• {} 로 생성>>> landvibe = {‘ 양욱’ , ‘ 성현’ , ‘ 재형’ , ‘ 양욱’ , ’ 성현’ }>>> landvibe{‘ 양욱’ , ‘ 성현’ , ‘ 재형’ }
항목 존재 유무 확인>>> ‘ 양욱’ in landvibeTrue>>> ‘ 메시’ in landvibeFalse
Set Type
>>> landvibe = {‘ 양욱’ , ‘ 성현’ , ‘ 재형’ }>>> landvibe.add(‘ 주아’ )>>> landvibe{‘ 양욱’ , ‘ 성현’ , ‘ 재형’ , ‘ 주아’ }
항목추가 : add()
>>> landvibe.update(“ 건희” , “ 규정” )>>> landvibe{‘ 양욱’ , ‘ 성현’ , ‘ 재형’ , ‘ 주아’ , ‘ 건희’ , ‘ 규정’ }
항목 여러개 추가 : update()
>>> landvibe.remove(‘ 양욱’ )>>> landvibe{‘ 성현’ , ‘ 재형’ , ‘ 주아’ , ‘ 건희’ , ‘ 규정’ }
항목 삭제 : remove()
Set Type
>>> landvibe = set(‘laaaaandviiibe’)>>> landvibe{‘l’, ‘a’, ‘n’, ‘d’, ‘v’, ‘i’, ‘b’, ‘e’}
합집합 , 교집합 , 차집합 , 여집합>>> a = { 1, 2, 3, 4 }>>> b = { 3, 4, 5, 6 }>>> a-b # 차집합{1, 2}>>> a | b # 합집합{ 1, 2, 3, 4, 5, 6}>>> a & b # 교집합{ 3, 4}>>> a ^ b # 여집합{1, 2, 5 ,6}
중복문자 제거
Dictionary Type• Mutable 한 데이터 구조• Map 의 구현체• Key, Value 쌍으로 하나의 노드가 구성된다• Key 는 중복 불가 , Key 들의 집합은 Set 의 성질을 가짐• {key:value} 로 생성>>> landvibe = {‘ 양욱’ : 97, ‘ 규정’ :92}>>> landvibe{‘ 양욱’ : 97, ‘ 규정’ :92}>>> type(landvibe)<class ‘dict’>>>> len(landvibe)2
Dictionary Type
>>> landvibe = {‘ 양욱’ : 97, ‘ 규정’ :92}>>> landvibe[‘ 준오’ ] = 94>>> landvibe{‘ 양욱’ : 97, ‘ 규정’ :92, ‘ 준오’ :94}>>> del landvibe[‘ 규정’ ]>>> landvibe{‘ 양욱’ : 97, ‘ 준오’ :94}>>> landvibe[‘ 준오’ ] = 95{‘ 양욱’ : 97, ‘ 준오’ :95}
추가 , 삭제 , 변경 : dict_name[key]=value
Dictionary Type
>>> landvibe = {‘ 양욱’ : 97, ‘ 규정’ :92, ‘ 준오’ : 95}>>> landvibe.keys()dict_keys([‘ 양욱’ , ‘ 규정’ , ‘ 준오’ ]) # set 의 성질을 가집니다>>> list(landvibe.keys()) # [index] 로 접근 불가능[‘ 양욱’ , ‘ 규정’ , ‘ 준오’ ]>>> sorted(landvibe.keys())[‘ 규정’ , ‘ 양욱’ , ‘ 준오’ ]
key 추출 : keys()
>>> list(landvibe.values())[97, 92, 95]
value 추출 : values()
Dictionary Type
>>> landvibe = {‘ 양욱’ : 97, ‘ 규정’ :92, ‘ 준오’ : 95}>>> ‘ 양욱’ in landvibeTrue>>> ‘ 진홍’ not in landvibeTrue
키 존재 , 누락 유무 확인
>>> landvibe = dict( [ (‘ 양욱’ , 97), (‘ 규정’ , 92), (‘ 준오’ , 95) ] )>>> landvibe{‘ 양욱’ : 97, ‘ 규정’ :92, ‘ 준오’ : 95}>>> landvibe = dict( 양욱 =97, 준오 =95)>>> landvibe{‘ 양욱’ : 97, ‘ 준오’ : 95}
형 변환 : dict( list( tuple(key,value) ) )
끝
수고 하셨습니다 .오늘은 숙제가 없습니다 .