KEMBAR78
Python datatype | PPTX
Study
Of Landvibe
Python - DataType
Outline
1. Overview
2. Built-in Type
3. Data Type
4. Input / Output
5. Mutable vs Immutable
6. Data Structure
Calling a function
Object instantiation
Overview - Example
import 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 Interpreter 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 Interpreter Output
Python Interpreter 쓰면 CPython
JVM 쓰면 Jython
CLR 쓰면 Ironpython
Interpreter = VM
(거의 같습니다)
Compile 과정은 High
Level Language의 공통적
인 특징입니다.
Built-in Type Hierarchy
Data Type – Preview
• 파이썬에서는 모든 것이 객체입니다.
123
a>>> 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
>>> 456
456
>>> 0
0
숫자 앞에 기호가 없으면 양수, +붙히면 양수, -붙히면 음수
>>> 123
123
>>> +123
123
>>> -123
-123
연속된 숫자는 리터럴 정수로 간주
Numeric Types
>>> 5+10
15
>>> 5-10
-5
/ 연산은 부동소숫점, // 연산은 몫, % 연산은 나머지 값
>>> 5/10
0.5
>>> 5//10
0
>>> 5%10
5
덧셈, 뺄셈, 곱셈, 나눗셈 가능, **는 n제곱
>>> 5*10
50
>>> 5/10
0.5
>>> 5/0
Taceback (most recent call lask):
File “<stdin>”, line 1, in <module>
ZeroDivisionError: division by zero
0으로 나누지 맙시다
>>> 2**10
1024
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 % 500
2400
>>> ((2400 // 500) * 500) + (2400 % 500)
2400
진수 변환
>>> 0b10
2
>>> 0o10
8
>>> 0x10
16
연산자 우선 순위
>>> 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.9
4.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 더하기 y
x - y x 빼기 y
x * y x 곱하기 y
x / 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 > 2
True
>>> 4 > 9 and 3 > 2
False
>>> not 4 > 9
True
간단한 예제!
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, complex
문자열형(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 = pockets
>>> 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 = pockets[:]
>>> 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
>>> a
NameError: 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 assginment
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
‘민승’
>>>b
1994
패킹 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 landvibe
True
>>> ‘메시’ in landvibe
False
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 landvibe
True
>>> ‘진홍’ not in landvibe
True
키 존재, 누락 유무 확인
>>> landvibe = dict( [ (‘양욱’, 97), (‘규정’, 92), (‘준오’, 95) ] )
>>> landvibe
{‘양욱’ : 97, ‘규정’ :92, ‘준오’ : 95}
>>> landvibe = dict(양욱=97, 준오=95)
>>> landvibe
{‘양욱’ : 97, ‘준오’ : 95}
형 변환 : dict( list( tuple(key,value) ) )
끝
수고 하셨습니다.
오늘은 숙제가 없습니다.

Python datatype

  • 1.
  • 2.
    Outline 1. Overview 2. Built-inType 3. Data Type 4. Input / Output 5. Mutable vs Immutable 6. Data Structure
  • 3.
    Calling a function Objectinstantiation Overview - Example import 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칸)
  • 4.
    Overview – Similaritiesto Java • Everything inherits from “object” • Large standard library • Garbage collection
  • 5.
    Overview – Differencesto 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
  • 6.
    Overview – PythonInterpreter Complier가 python code 를 컴파일해 서 .pyc file(byte code, intermediate code)로 변환시킨다 .py file (python code) Compiler .pyc file Interpreter Output Interpreter 가 .pyc file을 프로세스에 load하여 실행 시킨다
  • 7.
    Overview – PythonInterpreter 엥? 이거 자바 아니에요???? 자바는 컴파일러 언어 라면서요!?!?!?!?!!?
  • 8.
    Overview – PythonInterpreter Complier가 python code 를 컴파일해 서 .pyc file(byte code, intermediate code)로 변환시킨다 .py file (python code) Compiler .pyc file Interpreter Output Python Interpreter 쓰면 CPython JVM 쓰면 Jython CLR 쓰면 Ironpython Interpreter = VM (거의 같습니다) Compile 과정은 High Level Language의 공통적 인 특징입니다.
  • 9.
  • 10.
    Data Type –Preview • 파이썬에서는 모든 것이 객체입니다. 123 a>>> a=123 >>> print(a) 123
  • 11.
    Data Type –Preview • 변수 이름에 사용할 수 있는 문자 • 소문자(a~z) • 대문자(A~Z) • 숫자(0~9) • 언더스코어(_) 가능 • bominkyo13 • __landvibe • KoenHee_91 불가능 • 13je_jang • landvibe!@# • if
  • 12.
    Data Type –Preview • 예약어는 변수이름으로 사용불가
  • 13.
    Data Type • 데이터의공통된 특징과 용도에 따라 분류하여 정의한 것 • 숫자형 (Numeric Type) - Integer, float, complex • 논리형 (Boolean Type) - True, False • 문자열형 (String Type) - “This is String”
  • 14.
    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
  • 15.
    Numeric Types >>> 456 456 >>>0 0 숫자 앞에 기호가 없으면 양수, +붙히면 양수, -붙히면 음수 >>> 123 123 >>> +123 123 >>> -123 -123 연속된 숫자는 리터럴 정수로 간주
  • 16.
    Numeric Types >>> 5+10 15 >>>5-10 -5 / 연산은 부동소숫점, // 연산은 몫, % 연산은 나머지 값 >>> 5/10 0.5 >>> 5//10 0 >>> 5%10 5 덧셈, 뺄셈, 곱셈, 나눗셈 가능, **는 n제곱 >>> 5*10 50 >>> 5/10 0.5 >>> 5/0 Taceback (most recent call lask): File “<stdin>”, line 1, in <module> ZeroDivisionError: division by zero 0으로 나누지 맙시다 >>> 2**10 1024
  • 17.
    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() 함수 사용
  • 18.
    Numeric Types >>> 2400// 500 * 500 + 2400 % 500 2400 >>> ((2400 // 500) * 500) + (2400 % 500) 2400 진수 변환 >>> 0b10 2 >>> 0o10 8 >>> 0x10 16 연산자 우선 순위 >>> bin(10) ‘0b1010’ >>> oct(10) ‘0o12’ >>> hex(10) ‘0xa’ // str형으로 반환
  • 19.
    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.9 4.9 숫자의 타입을 섞어서 사용하면, 자동으로 형변환
  • 20.
    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
  • 21.
    Numeric Types • 정리 연산기호 결과 우선순위 x + y x 더하기 y x - y x 빼기 y x * y x 곱하기 y x / y x 나누기 y (float값) x // y x를 y로 나눈 값의 몫 x % y x를 y로 나눈 값의 나머지 -x 부호 변경 +x 변동 없음 x ** y x의 y제곱 낮음 높음
  • 22.
    Boolean Types 비교 연산자뜻 < 작은 <= 작거나 같은 > 큰 >= 크거나 같은 == 같은 != 같지 않은 is 같은 객체인 is not 같은 객체가 아 닌 논리 연산자 결 과 x or y x, y 중 하나만 참이면 참, 나머 지는 거짓 x and y x, y 모두 참이면 참, 나머지는 거 짓 not x x가 참이면 거짓, x가 거짓이면 참 • True & False
  • 23.
    Boolean Types >>> a=123123 >>>b=123123 >>> id(a) 25428720 >>> id(b) 25428704 >>> a is b # is는 id값을 비교 False >>> a == b # ==는 내용을 비교 True == vs is
  • 24.
    Boolean Types >>> 4> 9 or 3 > 2 True >>> 4 > 9 and 3 > 2 False >>> not 4 > 9 True 간단한 예제!
  • 25.
    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
  • 26.
    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
  • 27.
    String Types >>> pirnt(“허xx중간고사 점수:“ + 30) str()을 쓰는 이유? >>> pirnt(“허xx 중간고사 점수:“ + str(30)) 명시적으로 형변환이 필요할 때!
  • 28.
    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이기 때문에 배열처럼 사용 가능!
  • 29.
    String Types >>> print( “””보민아 공부좀 하자“””) 보민아 공부좀 하자 “””“””은 어따 쓰지? >>> s=“보민아 공부좀 하자” >>> len(s) 10 문자열의 길이 : len() >>> print(‘보민아n공부좀n하자’) 보민아 공부좀 하자 이스케이프 문자열 : n
  • 30.
    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’ 그 밖의 문자열 함수들
  • 31.
    String Types 다 외울필요 없습니다. 필요할 때마다 찾아쓰세요. 저도 다 몰라요
  • 32.
    Input & Output 표준입력 : input(‘질문 내용’) >>> deadline = input(‘양욱씨 통금이 몇시에요?’) ‘양욱씨 통금이 몇시에요?’ 11시 30분입니다 >>> deadline ‘11시 30분입니다’ input 함수의 반환값은 무조건 str입니다! >>> num = input(‘숫자를 입력하세요’) 숫자를 입력하세요 3 >>> num ‘3’ >>> type(num) <class ‘str’>
  • 33.
    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
  • 34.
    Mutable vs Immutable Mutable: 변할 수 있는 데이터형 Immutable : 변할 수 없는 데이터형, 변할 수 없으니 새로 생성! >>> hello = “안녕하세요” >>> a = id(hello) >>> hello = “반값습니다” >>> a == id(hello) # 식별자가 다르다!! False Immutable 예제 hello 변수의 값을 변경한게 아니라 메모리에 새로운 공간을 생성한다음에 그곳에 값을 복사한 것!
  • 35.
    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, complex 문자열형(string) 튜플형(tuple) 불편집합형(frozenset) 바이트형(bytes) 기억해두세요!!!!!!!!
  • 36.
    Data Structure • 데이터를활용 방식에 따라 조금 더 효율적으로 이용할 수 있도록 컴퓨터에 저장하는 여러방법 • 리스트형 (List Type) • 튜플형 (Tuple Type) • 세트형 (Set Type) • 사전형 (Dictionary Type)
  • 37.
    List Type • 하나의집합 단위로 동일한 변수에 순차적으로 저장 • 배열(Array)이라고 불리기도 함 • [] 로 선언 >>> pockets = [4, 6, 1, 9] 4 6 1 9리스트 pockets : 양수 index [0] [1] [2] [3] 음수 index [-4] [-3] [-2] [-1]
  • 38.
    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)
  • 39.
    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’>
  • 40.
    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]
  • 41.
    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]
  • 42.
    List Type • 리스트데이터 복사 = vs [:] >>> pockets = [4, 6, 1, 9] >>> pockets_copy = pockets >>> 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 = pockets[:] >>> pockets_copy [4, 6, 1, 9]
  • 43.
    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
  • 44.
    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]
  • 45.
    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 >>> a NameError: name ‘a’ is not defined
  • 46.
    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
  • 47.
    Tuple Type • Immutale한리스트형 • 다른 종류의 데이터형을 패킹 언패킹 할 때 사용 • 추가, 삭제, 자르기 불가능! • ()로 생성, but 생략 가능 >>> landvibe = ‘민승’, 1993, ‘우곤’, 1993 # ()괄호 생략가능 >>> landvibe (‘민승’, 1993, ‘우곤’, 1993) >>> landvibe[0] # 리스트처럼 인덱스 기능 사용 가능 ‘민승’ >>> landvibe[1:3] (1993, ‘우곤’, 1993)
  • 48.
    Tuple Type >>> landvibe= (‘민승’, 1994, ‘우곤’, 1994) >>> landvibe (‘민승’, 1994, ‘우곤’, 1994) >>> landvibe[0] = ‘건희’ TypeError: ‘tuple’ object does not support item assginment Tuple은 Immutable합니다! >>> landvibe = [‘민승’, 1994], [‘우곤’, 1994] >>> landvibe ([‘민승’, 1994], [‘우곤’, 1994]) >>> landvibe[1][0] = ‘건희’ 여기서 퀴즈!!! 결과는!?!?!?
  • 49.
    Tuple Type >>> landvibe= [‘민승’, 1994], [‘우곤’, 1994] >>> landvibe ([‘민승’, 1994], [‘우곤’, 1994]) >>> landvibe[1][0] = ‘건희’ >>> landvibe ([‘민승’, 1994], [‘건희’, 1994]) 정답! List는 Mutable 하기 때문에 가능합니다!
  • 50.
    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 빈튜플, 하나의 항목만 있는 튜플 생성시 주의사항
  • 51.
    Tuple Type >>> landvibe= ‘민승’, 1994, ‘우곤’, 1994 #이게 패킹 >>> a, b, c, d = landvibe #이게 언패킹 >>> a ‘민승’ >>>b 1994 패킹 vs 언패킹 형변환 - list(), tuple() 함수 사용 >>> landvibe_list= list(landvibe) >>> type(landvibe_list) <class ‘list’> >>> landvibe_tuple = tuple(landvibe_list) <class ‘tuple’>
  • 52.
    Set Type • Mutable한 데이터 구조 • Index, 순서가 없음 • 중복이 허용되지 않음 • {} 로 생성 >>> landvibe = {‘양욱’, ‘성현’, ‘재형’, ‘양욱’, ’성현’} >>> landvibe {‘양욱’, ‘성현’, ‘재형’} 항목 존재 유무 확인 >>> ‘양욱’ in landvibe True >>> ‘메시’ in landvibe False
  • 53.
    Set Type >>> landvibe= {‘양욱’, ‘성현’, ‘재형’} >>> landvibe.add(‘주아’) >>> landvibe {‘양욱’, ‘성현’, ‘재형’, ‘주아’} 항목추가 : add() >>> landvibe.update(“건희”, “규정”) >>> landvibe {‘양욱’, ‘성현’, ‘재형’, ‘주아’, ‘건희’, ‘규정’} 항목 여러개 추가 : update() >>> landvibe.remove(‘양욱’) >>> landvibe {‘성현’, ‘재형’, ‘주아’, ‘건희’, ‘규정’} 항목 삭제 : remove()
  • 54.
    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} 중복문자 제거
  • 55.
    Dictionary Type • Mutable한 데이터 구조 • Map의 구현체 • Key, Value 쌍으로 하나의 노드가 구성된다 • Key는 중복 불가, Key들의 집합은 Set의 성질을 가짐 • {key:value}로 생성 >>> landvibe = {‘양욱’ : 97, ‘규정’ :92} >>> landvibe {‘양욱’ : 97, ‘규정’ :92} >>> type(landvibe) <class ‘dict’> >>> len(landvibe) 2
  • 56.
    Dictionary Type >>> landvibe= {‘양욱’ : 97, ‘규정’ :92} >>> landvibe[‘준오’] = 94 >>> landvibe {‘양욱’ : 97, ‘규정’ :92, ‘준오’:94} >>> del landvibe[‘규정’] >>> landvibe {‘양욱’ : 97, ‘준오’:94} >>> landvibe[‘준오’] = 95 {‘양욱’ : 97, ‘준오’:95} 추가, 삭제, 변경 : dict_name[key]=value
  • 57.
    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()
  • 58.
    Dictionary Type >>> landvibe= {‘양욱’ : 97, ‘규정’ :92, ‘준오’ : 95} >>> ‘양욱’ in landvibe True >>> ‘진홍’ not in landvibe True 키 존재, 누락 유무 확인 >>> landvibe = dict( [ (‘양욱’, 97), (‘규정’, 92), (‘준오’, 95) ] ) >>> landvibe {‘양욱’ : 97, ‘규정’ :92, ‘준오’ : 95} >>> landvibe = dict(양욱=97, 준오=95) >>> landvibe {‘양욱’ : 97, ‘준오’ : 95} 형 변환 : dict( list( tuple(key,value) ) )
  • 59.