3. 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칸)
4. Overview – Similarities to Java
• Everything inherits from “object”
• Large standard library
• Garbage collection
5. 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
6. 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하여 실행
시킨다
7. Overview – Python Interpreter
엥? 이거 자바
아니에요????
자바는 컴파일러 언어
라면서요!?!?!?!?!!?
8. 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의 공통적
인 특징입니다.
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
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
연속된 숫자는 리터럴 정수로 간주
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
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]
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] = ‘건희’
여기서 퀴즈!!!
결과는!?!?!?
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