Professional Documents
Culture Documents
파이썬 기초강의 서강대 ocw - sogang - ac - kr
파이썬 기초강의 서강대 ocw - sogang - ac - kr
1. 시작하기
1. 소프트웨어 교육
2. 수업 목표
3. 파이썬 언어 소개
4. 파이썬 설치
5. hello world 출력
1. 소프트웨어 교육
미래 사회에서의 직업의 변화
소프트웨어 교육이란?
컴퓨팅의 기본적인 개념과 원리를 이해하고 그것을 바탕으로 문제
해결 능력을 키워주는 교육
2
1. 소프트웨어 교육
소프트웨어 교육의 구성
문제 해결 능력 함양 (컴퓨팅 사고력)
프로그래밍 언어에 대한 학습
프로그래밍 (코딩)
프로그램 - 컴퓨터가 특정 작업을 수행할 수 있도록 일련의
순서대로 작성한 명령어의 집합
3
2. 수업 목표
4
3. 파이썬(Python) 언어
파이썬 언어 버전
버전 2 : 2020년까지 지원 예정
버전 3 : 새로운 버전 (버전 2와 완벽하게 호환되지 않음)
5
4. 파이썬 설치
6
4. 파이썬 설치
7
4. 파이썬 설치
prompt
python shell
(interpreter)
8
5. hello world 출력
print 내장 함수
print() 함수는 괄호의 내용을 출력한다.
홑따옴표('…') 또는 쌍따옴표("…")를 이용하여 원하는 문자열을
출력할 수 있다.
홑따옴표 세 개('''…''') 또는 쌍따옴표 세 개("""... """)를 사용할 수
도 있다.
print('hello world')
print("hello world")
print('''hello world''')
print("""hello world""")
9
5. hello world 출력
③ 새로운 화면에서 코드 작성
④ File 메뉴에서 Save 선택
⑤ 파이썬 파일은 .py가 확장자임
11
5. hello world 출력
⑥ 저장한 코드 실행하기
‘Run’ 메뉴 → ‘Run Module’
⑦ Shell에 결과 출력됨
12
기초 PYTHON 프로그래밍
2. 객체, 변수, 자료형
1. 객체(object)와 변수(variable)
2. 객체 삭제하기
3. 자료형 (9가지)
4. 주석 (comment)
1. 객체(object)와 변수(variable)
중앙처리장치
(CPU) 모니터, 프린터
입력 장치 출력 장치
주기억장치 보조기억장치
(memory) (하드디스크)
2
CPU : Central Processing Unit
1. 객체(object)와 변수(variable)
객체(object)
메모리에 저장된 자료를 ‘객체’라고 부른다.
객체 생성하기 객체
a = 100 a 100 변수
변수명
3
1. 객체(object)와 변수(variable)
객체와 변수 예
>>> x = 100 1571577664 >>> type(x)
>>> y = 200 x 100 <class 'int'>
>>> z = x + y 1571579264 >>> type(y)
>>> print(x,y,z) y 200 <class 'int'>
100 200 300 >>> type(z)
61314544
>>> id(x) <class 'int'>
z 300
1571577664
>>> id(y)
= assignment (할당연산자)
1571579264
오른쪽의 값을 왼쪽 변수에 넣어라.
>>> id(z) = 의 왼쪽에는 변수가 와야 한다.
4
61314544
1. 객체(object)와 변수(variable)
변수명 만들기
변수명은 영어 소문자, 대문자, 숫자, _ (underscore)로만 구성한다.
변수명 예
>>> number = 5
>>> score = 90
>>> python_score = 95
>>> _score = 100
>>> math-score = 90 # syntax 에러. 특수 기호는 _ 만 가능하다
>>> math1 = 80
>>> 1math = 80 # syntax 에러. 숫자로 시작할 수 없다
7
3. 자료형
- str (문자열)
- list (리스트)
- tuple (튜플)
- set (집합)
- dict (사전)
8
3.1. 수치 자료형 – 정수형
정수형 (int)
정수형 자료는 10진수, 2진수, 8진수, 16진수가 있다.
>>> score = 23
>>> print(score) 1525430384
23 score 23
>>> type(score)
<class 'int'>
type(변수명) : 변수의 자료형을 알려준다.
>>> id(score)
id(변수명) : 변수의 식별자를 알려준다.
1525430384
9
3.1 수치 자료형 - 실수형
실수형 (float)
소수점을 포함하는 수이다.
10
3.1 수치 자료형 - 복소수
복소수형 (complex)
복소수형은 실수부와 허수부로 표현한다. 허수부 뒤에는 j 또는 J를
붙인다.
>>> x = 3 + 5j
>>> print(x)
54137944
(3+5j) x 3+5j
>>> type(x)
<class 'complex'>
>>> id(x)
54137944 11
3.2 부울형
부울형 (bool)
파이썬의 부울형은 참 / 거짓을 나타내는 True / False 의 두
값만을 갖는다.
12
3.3 문자열
문자열 (str)
따옴표를 이용하여 표현한다.
13
3.3 문자열
문자열 (str)
>>> city = "Seoul, Korea" # 쌍따옴표
>>> print(city)
Seoul, Korea
15
3.4 군집 자료형 - 튜플
튜플 (tuple) – 괄호 ( ) 로 표현한다.
리스트처럼 여러 개의 자료를 저장할 수 있다.
<class 'tuple'>
>>> id(data)
58257504
16
3.4 군집 자료형 - 집합
집합 (set) – { } 로 표현한다.
중복되지 않는 여러 개의 자료들을 모아서 저장해야 하는 경우에
집합을 사용한다.
사전 (dict)
키(key)와 값(value)의 쌍으로 구성되는 집합의 일종이다.
한 줄 주석 - # 기호를 사용함
# 숙제 1번
print('hello world')
print('python programming')
19
4. 주석 (comment)
""" 프로젝트 1.
작성자 : 홍길동
완성일 : 2016. 07. 31
프로젝트 버전 : 0.01
이 프로젝트는 파이썬 버전 3을 이용하였음 """
print('start of the program')
# 주요 코드 시작 부분
print('......')
정수 (int) 표현하기
>>> x = 100
>>> x = 100 ; y = 200
>>> y = 200
>>> print(x, y)
100 200 491051008
2
1. 정수 자료형과 연산
>>> a = 10 C 언어에서는…
>>> id(a) 4297546848
a = 10;
a X 10 a = 20;
4297546848
>>> a = 20 a 10 20
4297547168
>>> id(a) 20
mutable
4297547168 (수정가능함)
3
1. 정수 자료형과 연산
4
1. 정수 자료형과 연산
산술 연산자
연산자 의미 예 결과
항1 연산자 항2
+ 더하기 10 + 5 15
- 빼기 20 – 13 7
* 곱하기 3 * 10 30
피연산자
/ 나누기 100 / 8 12.5
** 지수계산 2 ** 5 32 4 // 결과
// 몫 30 // 7 4 7 30
% 나머지 30 % 7 2 28
2 % 결과
5
1. 정수 자료형과 연산
산술 연산자 우선순위
연산자 설명 결합 순서
** 지수 ←
* / % // 곱하기, 나누기, 나머지, 몫 →
+- 더하기, 빼기 →
>>> 2 + 3 * 5
17
>>> 2 ** 3 ** 2 # 2 ** 9
512
>>> (2 ** 3) ** 2 # 8 ** 2
64
>>> 2 ** 3 * 4
32
>>> 4 * 3 ** 2
36 6
1. 정수 자료형과 연산
할당 연산자와 산술 연산자 예제
>>> a = 10
>>> b = 20
>>> c = a + b # a와 b를 더하여 c에 저장하시오
>>> a = a + 50 # a의 값을 50 증가하시오
>>> b = b + a # b의 값을 a 만큼 증가하시오
>>> print(a, b, c)
60 80 30
7
1. 정수 자료형과 연산
산술 연산자 간략히 쓰기
a=a+b a += b >>> a = 10 ; b = 5 ; c = 22 ; d = 3
a=a*b a *= b >>> b -= d # b가 2가 됨
a = a ** b a **= b >>> c %= 5 # c가 2가 됨
a = a // b a //= b >>> a = 3; b = 2; c = 5; d = 10
a=a%b a %= b >>> d += b + c - a ** b # d가 8이 됨
8
2. 실수 자료형과 연산
실수 (float) 표현하기
소수점으로 표현하기
>>> a = 10.5
>>> b = 11.
>>> c = .5
>>> print(a,b,c)
10.5 11.0 0.5
9
2. 실수 자료형과 연산
실수의 특징
실수 객체도 immutable하다.
실수의 연산
정수 자료형에서 사용하는 연산자를 모두 사용할 수 있다.
>>> x = 2 + 5j
>>> y = 3.2 + 2.5J
>>> z = x + y
>>> print(z)
(5.2+7.5j)
>>> type(z)
<class 'complex'>
12
3. 복소수 자료형과 연산
복소수 연산하기
>>> x = 5 + 10j
>>> x.real # 실수부를 알려준다
5.0
>>> x.imag # 허수부를 알려준다
10.0
>>> x.conjugate() # 켤레복소수 반환한다
(5-10j)
13
4. 자료형 변환
수치 연산 관련 내장함수
함수 설명
abs(x) x의 절대값을 반환한다
divmod(x,y) (x//y, x%y) 쌍을 반환한다
pow(x,y) xy을 반환한다
>>> abs(-3)
3
>>> divmod(17,4)
(4, 1)
>>> pow(2,5)
32
16
6. math 모듈
1. 문자열 생성하기
2. 문자열 인덱싱 / 슬라이싱
3. 문자열 연결 / 반복
4. 문자열 길이 / 포함 관계
5. 문자열 메소드 사용하기
1. 문자열 생성하기
쌍따옴표(" … ")
3
1. 문자열 생성하기
5
1. 문자열 생성하기
print('''Dear Alice,
Sincerely,
Bob''')
6
2. 문자열 인덱싱 / 슬라이싱
문자열 객체의 특징
immutable하다.
인덱스 0 1 2 3 4 5 6 7 8 9 10
greeting h e l l o w o r l d
음수 인덱스 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
7
2. 문자열 인덱싱 / 슬라이싱
문자열 인덱싱
>>> greeting = 'hello world'
인덱스 0 1 2 3 4 5 6 7 8 9 10
greeting h e l l o w o r l d
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>> print(greeting[7])
o
>>> print(greeting[0])
h
>>> greeting[0] = 'H' # TypeError 발생
lang p y t h o n p r o g r a m m i n g
-18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
lang[a] – 인덱스 a의 문자
lang[a:b] – 인덱스 a부터 b-1까지의 문자열 (a < b)
lang[a:b:c]
• a<b, c>0 - a부터 b-1까지 c 간격의 문자열
• a>b, c<0 - a부터 b+1까지 c 간격의 문자열
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
lang p y t h o n p r o g r a m m i n g
-18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
11
3. 문자열 연결 / 반복
>>> a = 'hello'
>>> a * 3 # 문자열을 3회 반복한다
'hellohellohello'
12
4. 문자열 길이 / 포함 관계
문자열 길이 – len() 내장 함수
>>> dir(str)
['__add__', '__class__', ……'__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
14
5. 문자열 메소드 이용하기
메소드 설명
문자열을 모두 대문자로 바꾼다.
upper() >>> name = 'steve jobs'
>>> name.upper() # 'steve jobs'.upper()
'STEVE JOBS'
문자열을 모두 소문자로 바꾼다.
lower() >>> school = 'SOGANG University'
>>> school.lower()
'sogang university'
isupper() 메소드는 문자열이 모두 대문자이면 True를 반환한다.
islower() 메소드는 문자열이 모두 소문자이면 True를 반환한다.
isupper()
>>> a = 'hello'; b = 'WORLD'
islower() >>> a.islower()
True
>>> b.isupper()
True
15
5. 문자열 메소드 이용하기
메소드 설명
첫 문자를 대문자로 바꾼다.
메소드 설명
부분 문자열을 센다.
>>> state = 'mississippi'
>>> state.count('s')
4
count() >>> state.count('ssi')
2
>>> state.count('s', 5) # [5:]으로 잘라서 count한 결과
2
>>> state.count('s', 1, 5) # [1:5] 범위
2
부분 문자열 찾아서 첫 인덱스 알려 준다.
>>> state.find('s')
find() 2
>>> state.find('i', 5) # [5:] 범위에서 'i'를 찾는다
7 17
5. 문자열 메소드 이용하기
메소드 설명
문자열.join(리스트) – 리스트에 있는 자료들을 문자열로
연결한다.
출력문 – print() 내장 함수
출력문 – print() 내장 함수
print() 함수는 괄호의 내용을 출력한다.
출력하고자 하는 값이 여러 개인 경우에는 콤마로 구분할 수 있으며, 출력
할 때 각각의 값 사이에 공백 한 개가 추가된다.
문자열을 출력하려면 홑따옴표('…') 또는 쌍따옴표("…")를 이용한다.
(홑따옴표 세 개('''… '''), 쌍따옴표 세 개("""... """) 사용 가능)
>>> x = 10; y = 5; z = 7
>>> print(x,y,z)
10 5 7
>>> print('x')
x
>>> print(x)
10
3
1. print() 함수
4
1. print() 함수
문자열 출력하기
>>> print('hello world!')
hello world!
>>> print('hello', 'world!') # 콤마에 공백이 추가된다.
hello world!
>>> x = '5'
>>> print('hello' + 'world!')
>>> y = 5
helloworld!
>>> print(x)
>>> movie = 'toy story' 5
>>> print(y)
>>> print(movie) 5
toy story >>> x
'5'
>>> movie >>> y
'toy story' 5
5
1. print() 함수
+ 연산자
>>> x = '10'
>>> n = 100
>>> n + x # 에러
>>> n + int(x)
110
6
2. 특수 문자 출력
print() 함수 내에 사용하는 특수 문자
print() 함수 내에 사용하는 특수 문자
8
3. % 이용한 서식 출력
print(' '%( , ))
a = 'hello' a = 'hello\n'
b = 'world' b = 'world'
print(a) print(a)
print(b) print(b)
입력문 – input() 내장 함수
12
5. input() 함수
입력문 – input() 내장 함수
키보드로부터 입력을 받는다.
13
5. input() 함수
입력문 – input() 내장 함수
필요하다면 입력 받은 데이터의 자료형을 적절히 변환해야 한다.
입력문 – input() 내장 함수
일반적으로 다음과 같이 이용한다.
>>> x = int(input('Enter one integer : '))
Enter one integer : 100
>>> type(x)
<class 'int'>
2
문제 1.
kor = int(input('국어 성적을 입력하세요 : '))
math = int(input('수학 성적을 입력하세요 : '))
eng = int(input('영어 성적을 입력하세요 : '))
print()
print('입력받은 성적')
print('-' * 15)
4
문제 2.
5
문제 3.
6
문제 3.
n10000 = n // 10000
n = n % 10000
n1000 = n // 1000
n = n % 1000
n100 = n // 100
n = n % 100
n10 = n // 10
n1 = n % 10
print()
print('프로그램을 끝내려면 엔터를 누르세요.')
input() 7
기초 PYTHON 프로그래밍
7. 조건문
1. 불리언(Boolean) 표현식
2. 관계 연산자
3. 논리 연산자
4. if 조건문
5. 중첩된 if 조건문
1. 불리언(Boolean) 표현식
불리언 표현식의 예
3은 5보다 크다 → False
2
2. 관계 연산자
>>> x = 100
연산자 의미 >>> y = 200
> 크다 >>> x > y
>= 크거나 같다 False
< 작다 >>> x >= y
False
<= 작거나 같다
>>> x < y
== 같다 True
!= 같지 않다 >>> x <= y
True
>>> x == y
False
>>> x != y
True 3
3. 논리 연산자
논리 연산자
not, and, or 세 종류가 있다.
논리 연산자 설명
논리 연산자의 예
a = 10
b = 20
조건 논리
특정 조건에 따라 명령을 선택적으로 수행해야 하는 경우
조건 논리 유형 1
조건이 참인 경우에만 어떤 특정 명령을 실행한다.
T F
조건 if 조건 :
명령문 명령문
… ……
명령문 명령문
명령문
명령문
……
… 명령문
명령문
7
4. if 조건문
조건 논리 유형 1 예제
성적(score)을 입력받는다.
if score >= 70 :
print('축하합니다')
print('수고하셨습니다')
8
4. if 조건문
조건 논리 유형 2 예제
하나의 정수를 입력받는다.
그 수가 짝수이면 ‘짝수입니다’와 ‘프로그램 종료’를 출력한다.
그 수가 홀수이면 ‘홀수입니다’와 ‘프로그램 종료’를 출력한다.
if number%2 == 0 :
print(number, '는 짝수입니다.')
else :
print(number, '는 홀수입니다.')
print('프로그램 종료')
9
4. if 조건문
조건 논리 유형 2 예제 – 두 수 중에서 큰 수 출력하기
a = int(input('Enter a : '))
b = int(input('Enter b : '))
if a > b :
max = a if a > b : max = a
else: else : max = b
max = b
조건문에 해당하는 블록이 한 줄인
print(max)
경우 콜론 옆에 작성하기도 한다.
10
4. if 조건문
조건 논리 유형 3 if 조건1 :
A
T F
조건1 elif 조건2 :
B
T F
조건2 elif 조건3 :
T F C
조건3
…
elif 조건n :
……
A B C …
else :
명령문 …
…
명령문 명령문
11
4. if 조건문
조건 논리 유형 3 예제
성적을 입력받는다.
12
4. if 조건문
조건 논리 유형 3 예제
score = int(input('성적을 입력하시오 : '))
if score >= 90 :
grade = 'A'
elif 80 <= score < 90 : # elif 80 <= score :
grade = 'B'
elif 70 <= score < 80 : # elif 70 <= score :
grade = 'C'
else:
grade = 'D'
13
5. 중첩된 if 조건문
중첩된 if 조건문 형태
if 조건A :
명령어 A
if 조건1 :
명령어 1
elif 조건2 :
명령어 2
else :
명령어 3
elif 조건B :
명령어 B
else :
명령어 C
명령어 D 14
5. 중첩된 if 조건문
중첩된 if 조건문 예제
성적을 입력받는다.
- ‘통과하셨습니다’를 출력한다.
중첩된 if 조건문 예제
if score >= 70 :
print('통과하셨습니다.')
if score >= 90 :
print('A장학금 지급 대상자입니다.')
elif score >= 80 :
print('B장학금 지급 대상자입니다.')
elif score >= 60 :
print('조건부 통과자입니다.')
else:
print('재수강 대상자입니다.')
print('수고하셨습니다.')
16
기초 PYTHON 프로그래밍
8. while 반복문
1. 반복 논리
2. 파이썬의 두 가지 반복문
3. while 반복문
4. 중첩된 while 반복문
1. 반복 논리
반복 논리
특정 명령 또는 연산을 반복적 F
조건
으로 수행해야 하는 경우 T
명령문 1
반복을 제어할 조건문이 있어야
한다. 명령문 2
명령문 n
명령문 n+1
2
2. 파이썬의 두 가지 반복문
3
3. while 반복문
a=1
while a <= 5 :
print(a)
a += 1
4
3. while 반복문
예제 2 : 1부터 10까지의 합
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = ?
a sum
a=1 1 0
2 1
sum = 0
3 3
while a <= 10 : 4 6
sum += a 5 10
6 15
a += 1
7 21
print('sum :', sum) 8 28
9 36
sum(range(11)) 10 45 5
55
3. while 반복문
a=2 a=1
sum = 0 sum = 0
while a <= 10 : while a <= 10 :
sum += a if a % 2 == 0 :
a += 2 sum += a
print('sum :', sum) a += 1
print('sum :', sum) 6
4. while 반복문 제어하기
무한루프와 break
a=1
while True :
print(a)
if a == 5 : break
a += 1
8
4. while 반복문 제어하기
a=1 a=0
while a <= 10 :
while a <= 10 :
…… a += 1
…… if a%3 == 0 :
if 조건 : continue
print('a =',a)
continue
…… print('after while')
……
a += 1 continue 조건이 참인 경우 continue
…… 아래 부분은 실행하지 않는다. 9
……
5. 중첩된 while 반복문
10
5. 중첩된 while 반복문
dan = 2
2
문제 1.
if working_hour > 12 :
additional_pay = (working_hour - 12) * pay_per_hour * 0.3
total_pay += additional_pay
print()
print('총 급여는', total_pay, '원입니다.')
3
문제 2.
4
문제 2.
a=1
count = 0
while a <= n :
if n % a == 0 :
print(a)
count += 1
a += 1
print()
print(n, '의 약수의 개수 :', count)
5
문제 3.
6
문제 3.
loop_count = 1
while loop_count <= 4:
n = int(input('정수를 입력하시오 : '))
if n > max :
max = n
loop_count += 1
print()
print('가장 큰 값 :', max)
7
기초 PYTHON 프로그래밍
10. 리스트(list), 튜플(tuple)
1. 리스트와 연산
2. 리스트 사용하기
3. 튜플과 연산
4. 튜플 사용하기
1. 리스트와 연산
리스트는 mutable 하다
>>> print(score[2])
>>> score[2] = 78 # mutable
75
>>> print(score)
>>> print(score[-2])
[80, 90, 78, 88, 92]
88
2
1. 리스트와 연산
슬라이싱 (slicing)
A = [15, 27, 32, 20, 17, 13, 10, 22]
0 1 2 3 4 5 6 7
15 27 32 20 17 13 10 22
-8 -7 -6 -5 -4 -3 -2 -1
슬라이싱 (slicing)
B = ['a','b','c','d','e','f','g','h','i','j','k']
0 1 2 3 4 5 6 7 8 9 10
a b c d e f g h i j k
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
B[::] # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
B[2:9:3] # ['c', 'f', 'i']
B[0:-1:2] # ['a', 'c', 'e', 'g', 'i']
B[::2] # ['a', 'c', 'e', 'g', 'i', 'k']
B[-1:-7:-2] # ['k', 'i', 'g']
4
1. 리스트와 연산
>>> K = L + M
>>> print(K)
[1, 3, 5, 7, 9, 2, 4, 6, 8]
>>> L = [1,3,5,7,9]
>>> 7 in L # 리스트 L에 데이터 7이 있다면 True
True
>>> 10 in L
False
>>> 10 not in L # 리스트 L에 데이터 10이 없다면 True
True
>>> len(L)
5
6
2. 리스트 사용하기
>>> dir(list)
['__add__', '__class__', …… '__subclasshook__', 'append',
'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
7
2. 리스트 사용하기
메소드 설명
append (x) 데이터 x를 리스트 끝에 추가한다.
clear() 리스트를 비운다.
copy() 리스트를 복사한다.
count (x) 데이터 x의 개수를 알아낸다.
extend (M) 리스트 M을 연결한다.
index (x) 데이터 x의 위치를 알아낸다 (인덱스를 알려준다).
insert (i,x) 데이터 x를 지정한 위치 (인덱스 i)에 삽입한다.
pop() 리스트의 지정한 값 하나를 읽어 내고 삭제한다.
remove (x) 리스트에서 데이터 x를 삭제한다.
reverse() 리스트의 순서를 역순으로 바꾼다.
sort() 리스트를 정렬한다.
8
2. 리스트 사용하기
>>> L = [1,4,7,8]
>>> L.append(5)
>>> print(L)
[1, 4, 7, 8, 5]
>>> L.insert(2,10)
>>> print(L)
[1, 4, 10, 7, 8, 5]
9
2. 리스트 사용하기
>>> L = ['g','a','c','f','g','b']
>>> L.index('f')
3
>>> L.index('g') # 데이터가 여러 개이면 첫 번째 인덱스 반환
0
>>> L.count('g')
2
>>> L.count('b')
1
>>> L.count('m')
0 11
2. 리스트 사용하기
>>> A = [] # 빈 리스트
>>> A.append('red')
>>> A.append('blue')
>>> A.append('yellow')
>>> print(A)
['red', 'blue', 'yellow']
>>> A.clear()
>>> print(A)
[]
12
2. 리스트 사용하기
[1, 3, 5, 7, 9]
2324360
>>> print(N)
N 1 3 5 7 9
[1, 3, 100, 7, 9]
>>> id(L)
53794216
>>> id(N)
14
2324360
2. 리스트 사용하기
>>> L = [1,3,5]
>>> M = [10,20]
>>> L.extend(M) # L에 M를 연결한다.
>>> print(L)
[1, 3, 5, 10, 20]
>>> print(M)
[10, 20]
15
2. 리스트 사용하기
>>> L = [3,5,1,4,2]
>>> L.sort() # 오름차순으로 정렬
>>> print(L)
[1, 2, 3, 4, 5]
>>> L = [3,5,1,4,2]
>>> L.sort(reverse=True) # 내림차순으로 정렬
>>> print(L)
[5, 4, 3, 2, 1]
16
2. 리스트 사용하기
>>> L = [3,5,1,4,2]
>>> L.reverse()
>>> print(L)
[2, 4, 1, 5, 3]
17
3. 튜플과 연산
[] 대신에 ( )를 사용
18
3. 튜플과 연산
>>> T = (1,3,5,7,9)
index → 0 1 2 3 4
>>> M = (2,4,6,8) T 1 3 5 7 9
>>> print(T[2]) index → -5 -4 -3 -2 -1
5
>>> L + M
(1, 3, 5, 7, 9, 2, 4, 6, 8) 튜플에서는 다음과 같이 데이터를 바꾸는 일이 불가능하다.
(2, 4, 6, 8, 2, 4, 6, 8) ……
TypeError: 'tuple' object does not support item
>>> 7 in L
assignment
True
>>> len(L)
5 19
4. 튜플 사용하기
메소드 설명
index(x) 튜플에서 데이터 x의 인덱스를 반환한다.
count(x) 튜플에서 데이터 x의 개수를 반환한다.
>>> T = (4,3,5,7,6,5,7,4,7,2)
>>> T.count(7) # 7의 개수
3
>>> T.index(2) # 데이터 2의 첫 번째 인덱스
9
>>> T.index(7) # 데이터 7의 첫 번째 인덱스. 없으면 에러 발생.
3
>>> dir(tuple)
['__add__', '__class__', ……'__subclasshook__', 'count', 'index']
20
4. 튜플 사용하기
빈 튜플 T = ()
T = tuple()
튜플 이용한 swap
>>> x=10; y=20
튜플은 함수에서 유용하게 사용된다.
>>> print(x,y)
튜플은 immutable하므로 프로그램 수행 동안
10 20
변경하지 않아야 하는 데이터는 튜플로 저장하
>>> x,y = y,x
는 것이 좋다.
>>> print(x,y)
20 10
22
기초 PYTHON 프로그래밍
11. 집합(set), 사전(dict)
1. 집합 (set)
2. 집합 사용하기
3. 사전 (dict)
4. 사전 사용하기
1. 집합 (set)
mutable 자료형이다.
메소드 설명
add (x) 집합에 원소 x를 추가한다.
clear() 공집합으로 만든다.
copy () 집합을 복사한다.
집합에서 원소 x를 삭제한다. 없는 원소를 삭제하려고 할
discard (x)
때에도 에러를 발생하지 않는다. (remove와 비교)
집합에서 임의의 원소를 하나 가져온다. 어떤 원소를 가져
pop()
올 지 알 수 없다. 집합에서 그 원소는 삭제된다.
집합에서 원소 x를 삭제한다. 없는 원소를 삭제하려고 하면
remove (x)
에러가 발생한다.
>>> dir(set)
['__and__', '__class__', …… '__xor__', 'add', 'clear', 'copy', 'difference',
'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint',
'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference',
'symmetric_difference_update', 'union', 'update'] 3
2. 집합 사용하기
집합에 원소 추가하기
>>> A = {4,2,6,8,3}
>>> print(A)
{8, 2, 3, 4, 6}
>>> A.add(5) # 집합 A에 데이터 5를 추가한다.
>>> print(A)
{2, 3, 4, 5, 6, 8}
>>> A.add(3) # 이미 있는 데이터를 추가하면 변동이 없다.
>>> print(A)
{2, 3, 4, 5, 6, 8}
4
2. 집합 사용하기
집합에서 원소 삭제하기
>>> A = {4,6,2,5,3}
>>> A.discard(5)
>>> print(A)
{2, 3, 4, 6}
>>> A.discard(7) # 집합 A에 없는 원소 삭제해도 에러 없다.
>>> print(A)
{2, 3, 4, 6}
5
2. 집합 사용하기
>>> A = {1,3,5,6,4}
>>> A.pop() # pop 메소드는 집합에서 임의의 원소를 반환하고 삭제한다.
1
>>> print(A)
{3, 4, 5, 6}
>>> A.clear() # 집합 A를 공집합으로 만든다.
>>> print(A)
set()
6
3. 사전 (dict)
사전 예
1반 25명, 2반 30명, 3반 27명이라는 정보를 저장하고자 한다.
사전의 키
mutable 자료형은 ‘키’가 될 수 없다. (리스트, 집합, 사전)
사전의 값
모든 자료형이 사전의 ‘값’이 될 수 있다.
빈 사전 생성하기
8
3. 사전 (dict)
9
3. 사전 (dict)
10
4. 사전 사용하기
>>> dir(dict)
['__class__', '__contains__', ……'__subclasshook__', 'clear',
'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem',
'setdefault', 'update', 'values']
메소드 설명
clear () 사전의 내용을 모두 지운다.
copy () 사전을 복사한다.
items() 사전에 있는 모든 데이터의 (키,값)을 모두 반환한다.
keys() 사전에서 키만 반환한다.
values() 사전에서 값만 반환한다.
update(D) 사전 D를 추가한다.
11
4. 사전 사용하기
clear() 메소드
12
4. 사전 사용하기
{1: 30, 2: 25, 3: 27, 4: 32} {1: 30, 2: 25, 3: 27, 4: 32} 13
4. 사전 사용하기
update(D) 메소드
14
4. 사전 사용하기
>>> B = list(count.items())
>>> print(B)
[('sat', 25), ('toefl', 40), ('toeic', 50)]
15
4. 사전 사용하기
>>> B = list(count.keys())
>>> print(B)
['sat', 'toefl', 'toeic']
16
4. 사전 사용하기
>>> A = count.values()
>>> print(A)
dict_values([25, 40, 50])
>>> B = list(count.values())
>>> print(B)
[25, 40, 50]
17
기초 PYTHON 프로그래밍
12. for 반복문
1. range() 함수
2. for 반복문
3. 리스트 내에 for 반복문
4. 군집자료형의 형변환
1. range() 함수
3
3. range() 함수와 for 반복문
예제 1
for x in range(5):
print(x)
range(5) 자리에 [0,1,2,3,4]가 온다.
차례대로 x값이 되어 for 블록을 수행한다.
예제 2
for data in range(1,10,2):
print(data+1)
4
4. 문자열과 for 반복문
예제 3
for letter in 'PYTHON':
print(letter)
'PYTHON'이 하나씩 letter 변수에 저장되어
for 블록을 수행한다.
예제 4
for alpha in 'sogang':
y = alpha.upper()
print(y)
5
5. 리스트와 for 반복문
예제 5
for x in [1,3,5,7,9]:
print(x)
예제 6
for x in [1,2,3,4,5]:
for y in [2,4,6,8,10]:
print(x*y, end=' ')
print() 6
6. 사전과 for 반복문
예제 7
for x in score :
print(x)
예제 8
for x in score.keys():
print(x)
7
6. 사전과 for 반복문
예제 9
for x,y in score.items() :
print(x,y)
8
6. 사전과 for 반복문
예제 10
for x in score.values() :
print(x)
9
7. 리스트 안에 for 반복문 사용하기
A = { x2 : x ∈ {0, 1, 2, …, 9} }
B = { 1, 2, 22, 23, …, 210 } [ 표현식 for x in 데이터집합 if 조건 ]
C = { x | x ∈ A and x is even }
함수명 설명 A = [1,2,3,4]
str(A) A를 문자열로 변환한다. B = (1,3,5)
list(A) A를 리스트로 변환한다. C = {2,4,6,8,10}
tuple(A) A를 튜플로 변환한다. D = {1:90, 2:88, 3:93}
set(A) A를 집합으로 변환한다.
E = tuple(A) # (1, 2, 3, 4)
dict(A) A를 사전으로 변환한다.
F = set(B) # {1, 3, 5}
G = list(C) # [8, 10, 2, 4, 6]
H = list(D) #[1, 2, 3]
I = tuple(D) # (1, 2, 3)
J = set(D) # {1, 2, 3}
11
기초 PYTHON 프로그래밍
13. 실습 3
문제 1.
2
문제 1.
for x in range(10):
print(x, end=' ')
print()
print()
3
문제 2.
4
문제 2.
score = []
for i in range(5):
data = int(input('성적을 입력하시오 : '))
score.append(data)
print()
print('입력한 성적들 :', score)
print('최고 성적 :', max(score))
print('최저 성적 :', min(score))
5
문제 3.
번호 국어 영어 수학
1 80 90 86
2 78 88 85
3 85 85 92
4 70 69 65
5 90 95 100
6
문제 3.
score = {1:[80,90,86],
2:[78,88,85],
3:[85,85,92],
4:[70,69,65],
5:[90,95,100]}
7
기초 PYTHON 프로그래밍
14. 함수 - 1
1. 함수
2. 파이썬 내장 함수
3. 사용자 정의 함수
4. 함수의 인수와 반환값
5. 함수의 위치와 main 작성하기
1. 함수
2
2. 파이썬 내장 함수
내장 함수 (built-in functions)
파이썬 언어에서 미리 만들어서 제공하는 함수들
>>> dir(__builtins__)
['ArithmeticError', …… 'ZeroDivisionError', '_', '__build_class__',
'__debug__', '__doc__', '__import__', '__loader__', '__name__',
'__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray',
'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright',
'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash',
'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object',
'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr',
'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str',
'sum', 'super', 'tuple', 'type', 'vars', 'zip'] 4
2. 파이썬 내장 함수
>>> L = [1,3,5,7,9]
>>> M = reversed(L)
>>> print(M)
<list_reverseiterator object at 0x03DC92B0>
>>> M = list(reversed(L))
>>> print(M)
[9, 7, 5, 3, 1]
>>> T = (2,4,6,8) >>> S = 'HELLO'
>>> K = list(reversed(T)) >>> P = list(reversed(S))
>>> print(K) >>> print(P)
[8, 6, 4, 2] ['O', 'L', 'L', 'E', 'H'] 6
3. 사용자 정의 함수
함수 정의하기
parameter
def 함수명 ( parameter ) : (매개변수)
a b
""" 이 함수는 두 정수에서 큰 값 함수명 : find_max
을 찾아서 반환하는 함수이다. """ def find_max (a,b):
if a > b :
if a > b :
y=a
y=a
else : else :
y=b y=b
return 반환값
return y
# main
인수, 반환값이 없는 함수
함수에 입력이 없으면 빈 괄호로 둔다.
# main
kor_score = int(input('국어 성적을 입력하시오 : '))
eng_score = int(input('영어 성적을 입력하시오 : '))
math_score = int(input('수학 성적을 입력하시오 : '))
11
4. 함수의 인수와 반환값
반환값이 여러 개인 경우
함수에 반환값이 2개 이상인 경우 튜플로 묶어서 반환한다.
예) 두 수를 입력받아서 두 수의 합과 두 수의 곱을 반환하는 함수
def add_multiply(x,y):
sum = x + y
mult = x * y
return sum, mult # 튜플로 반환한다.
# main
a = int(input('Enter a : '))
b = int(input('Enter b : '))
m,n = add_multiply(a,b)
print(m,n)
12
5. 함수의 위치와 main 작성하기
함수의 위치
함수는 호출 전에 정의되어 있어야 한다.
print('start of the program') a = 10
hello() b = 20
print('middle of the program') print('before test definition')
hello()
print('end of the program') def test():
print('I am test')
def hello(): print(a, b)
print('hello world')
print('start')
test()
print('end')
13
5. 함수의 main 작성하기
main 함수 작성하기
main은 프로그램 시작점을 의미한다.
if __name__ == '__main__':
main()
14
기초 PYTHON 프로그래밍
15. 함수 - 2
1. 전역 변수와 지역 변수
2. 함수의 인수
3. 람다 함수 (lambda)
1. 전역 변수와 지역 변수
global 선언
전역 변수를 함수 내에서 바꾸고자 하면, global 선언이 필요함
3
1. 전역 변수와 지역 변수
global 선언
함수에서 만든 지역 변수를 전역 변수로 사용하고자 한다면 global 선
언이 필요함
함수 매개변수는 지역 변수이다.
def test(a):
a += 200 지역 변수 a
print(a)
# main
a = 100 전역 변수 a
test(a)
print(a)
# main
만약에 L 복사본이 생겨서 원본 L을 바꾸고
싶지 않다면 다음과 같이 test 함수에 인수
L = [90,80,95,85,77,83] 를 넘겨야 한다.
test(L)
print(L) test(L[:]) 또는 test(L[::])
6
2. 함수의 인수
기본값(default value)이 있는 인수
함수를 호출할 때 인수를 넘겨주지 않아도 인수가 자신의 기본값을 취
하도록 하는 기능.
7
2. 함수의 인수
키워드 인수
함수 호출 시에 인수 이름(매개변수)과 값을 같이 전달하기
a = area(10,5)
b = area(x=4, y=9) # 매개변수와 값을 같이 적어 준다
c = area(y=5, x=10) # 매개변수와 값을 같이 적으면 순서 상관없다
d = area(10, y=5) # OK (일반 인수 뒤에 키워드 인수 올 수 있다)
e = area(x=10, 5) # 에러
9
2. 함수의 인수
키워드 인수
키워드 인수의 위치는 일반 인수 이후이다.
def volume(x,y,z):
일반 인수 : positional argument
return x * y * z
volume(1, 3, 5) # 15
volume(y=7, z=5, x=2) # 70
volume(z=2, x=4, y=5) # 40
volume(5, z=10, y=2) # 100
volume(5, x=2, z=20) # 에러 (x에 두 개의 값이 할당된다는 에러)
volume(z=10, 20, x=2) # 에러 (일반 인수가 키워드 인수 뒤에 오면 안됨)
10
2. 함수의 인수
가변 인수 사용하기
정해지지 않은 수의 인수를 함수에 전달하기
def name_age(**lists):
print(lists)
name_age(Alice=10, Paul=12)
print('-----------------------------')
name_age(Cindy=5, David=7, Tom=10)
12
3. 람다 함수 (lambda)
람다 함수의 정의
이름없는 한 줄짜리 함수이다.
def add(x,y):
lambda x, y: x + y
return x+y
13
3. 람다 함수 (lambda)
map 내장 함수
map( 함수명 , 함수에 대한 인수 집합 )
map 내장 함수 예
>>> def f(x):
return x * x
>>> X = [1, 2, 3, 4, 5]
>>> list(map( f, X )) # 함수 f 에 X의 값들을 하나씩 적용한다
[1, 4, 9, 16, 25]
>>> X = [1, 2, 3, 4, 5]
>>> Y = map( lambda a:a * a, X )
>>> list(Y)
[1, 4, 9, 16, 25]
filter 내장 함수
>>> X = [1,3,5,7,9]
>>> result = filter( lambda x:x>5, X )
>>> print(result)
<filter object at 0x03FAD0D0>
>>> list(result)
[7, 9]
1. 모듈 소개하기
2. 모듈 사용하기
3. 모듈 만들기
4. random 모듈
1. 모듈 소개하기
파이썬 구성 요소
modules + classes + built-in functions (내장함수)
math module
pow () class str
sin() class list upper ()
cos() …… lower()
append () count() ……
insert()
…… module들 sort() ……
…… class들
2
1. 모듈 소개하기
모듈 (module)
코드들을 한 단위로 묶어 사용할 수 있게 하는 하나의 단위.
모듈의 종류
① 표준 모듈 – 파이썬 패키지 안에 포함된 모듈
모듈 사용의 장점
① 코드의 재사용성
3
2. 모듈 사용하기
>>> math.pi
3.141592653589793
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos',
'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial',
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf',
'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'pi',
'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
4
2. 모듈 사용하기
모듈 import 방법
① import <모듈>
5
2. 모듈 사용하기
모듈 import 방법
② from <모듈> import <함수명>
>>> from math import pow
>>> pow(2,5) # 이 경우 함수명만 사용 가능하다
32.0
>>> from math import pow, sqrt, trunc # 콤마로 여러 함수 사용 가능
>>> sqrt(9)
3.0
>>> trunc(1.5)
1
>>> pow(2,3)
8.0
>>> from math import * # math 모듈에 있는 모든 함수를 이름으로 사용
>>> log2(1024)
6
10.0
2. 모듈 사용하기
모듈 import 방법
③ import <모듈> as <alias>
7
3. 모듈 만들기
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence',
'_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst',
'_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator',
'_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate',
'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate',
'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
9
4. random 모듈
함수 설명
randint(a,b) a<=N<=b 사이의 임의의 정수 N 선택
정수 선택
randrange( ,,) range() 결과 중에서 임의의 값 선택
random() 0.0 <= F < 1.0 사이의 임의의 실수 F 선택
실수 선택
uniform(a,b) a와 b 사이의 임의의 실수 선택
10
4. random 모듈
임의의 정수 생성 (randint())
11
4. random 모듈
임의의 정수 생성 (randrange())
12
4. random 모듈
임의의 정수 여러 개 생성
13
4. random 모듈
>>> T = tuple(range(1,10,2))
>>> print(T)
(1, 3, 5, 7, 9)
>>> random.choice(T)
7
>>> random.sample(T,2)
[1, 7]
>>> random.shuffle(T) # 에러
16
4. random 모듈
>>> w = 'abcdefghijklmn'
>>> random.choice(w)
'b'
>>> random.choice(w)
'l'
>>> random.sample(w,3)
['n', 'c', 'a']
>>> random.shuffle(w) # 에러
17
기초 PYTHON 프로그래밍
17. 실습 4
문제 1.
2
문제 1.
# main
print()
print('총 급여는', int(answer), '원입니다.')
3
문제 2.
화씨 = 섭씨 * 9 / 5 + 32
4
문제 2.
def CtoF(temp):
result = temp * 9 / 5 + 32
return result
# main
print()
for t in range(start_temp, end_temp+1):
r = CtoF(t)
print('섭씨 %.2f도는 화씨 %.2f도입니다.' % (t,r))
5
문제 3.
6
문제 3.
import random
number = random.randint(1,100)
1. 구문 에러
2. 예외
3. 예외 처리
1. 구문 에러
구문 에러 (syntax error)
문법 에러
>>> a = 100
>>> if a > 100 ; print(a)
2
2. 예외
예외(exception)
구문 에러가 없이 잘 작성된 코드라도 실행 도중에 에러가 발생할 수
있다. 이러한 잠재적인 에러를 ‘예외’라고 한다.
>>> print(x)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print(x)
NameError: name 'x' is not defined
>>> a = 1 ; b = 'A'
>>> a + b
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
a+b
TypeError: unsupported operand type(s) for +: …… 3
2. 예외
예외(exception)
>>> a = 10; b = 0
>>> a / b
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a/b
ZeroDivisionError: division by zero
>>> L = [1,2,3]
>>> print(L[3])
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print(L[3])
IndexError: list index out of range
4
3. 예외 처리
예외 처리 예
a = int(input('Enter a : '))
b = int(input('Enter b : '))
c=a/b
print(c)
5
3. 예외 처리
예외 처리 예
a = int(input('Enter a : '))
b = int(input('Enter b : '))
try :
c=a/b
print(c)
except ZeroDivisionError :
print('Cannot divide by 0')
6
3. 예외 처리
예외 처리
try :
< 예외 발생 가능성이 있는 문장 >
except < 예외 종류 > :
< 예외 처리 문장 >
except < 예외 종류 > :
< 예외 처리 문장 >
else :
< 예외가 발생하지 않은 경우, 수행할 문장 >
finally :
< 예외 발생 유무에 상관없이 try 블록 이후 수행할 문장 >
7
3. 예외 처리
a=5
예외 처리 예 b=0
L = [1,2,3]
a=5 print('hello')
b=0 try :
L = [1,2,3] c=a/b
print(x)
print('hello') print(L[3])
except ZeroDivisionError:
c=a/b print('cannot divide by zero !!!')
print(x) except NameError:
print(L[3]) print('no variable named "x"')
except IndexError:
print('out of indexing in list')
print('good bye') else:
print('else part')
print('good bye') 8
3. 예외 처리
a=5
예외 처리 예 b=1 수정하였음.
L = [1,2,3]
print('hello')
try :
c=a/b
print(x)
print(L[3])
except ZeroDivisionError:
print('cannot divide by zero !!!')
except NameError:
print('no variable named "x"')
except IndexError:
print('out of indexing in list')
else:
print('else part')
print('good bye') 9
3. 예외 처리
try :
c=a/b
print(L[2])
except ZeroDivisionError:
print('cannot divide by zero !!!')
except IndexError:
print('out of indexing in list')
else:
print('else part')
10
print('good bye')
3. 예외 처리
L = [1,2,3] 예외 발생 예제
print('hello')
try:
print(L[3])
except IndexError:
print('out of indexing in list')
else:
print('else part')
finally:
print('finally part')
print('good bye')
11
3. 예외 처리
L = [1,2,3] 예외 없는 예제
print('hello')
try:
print(L[2]) 수정하였음.
except IndexError:
print('out of indexing in list')
else:
print('else part')
finally:
print('finally part')
print('good bye')
12
기초 PYTHON 프로그래밍
19. 파일 입출력
1. 파일 연결 – open() 내장 함수
2. 파일 입력 - 파일로부터 데이터 읽어오기
3. 파일 출력 - 파일에 데이터 저장하기
1. 파일 연결
open() 내장 함수
file 파일명
파일을 열 때의 모드를 의미하며, 다음 문자열 조합으로 사
용함.
mode • r : 읽기 모드 (디폴트)
• w : 쓰기 모드
• a : 쓰기 + 이어쓰기 모드 (append)
• r+ : 읽기와 쓰기를 모두 하고자 할 때
2
1. 파일 연결
3
2. 파일 입력
read()와 read(n)
f = open('newfile.txt', 'r')
a = f.read(4)
print(a)
b = f.read()
print(b)
f.close()
4
2. 파일 입력
한 줄씩 읽어 오기 - readline()
f = open('about.txt', 'r')
a = f.readline()
print(a)
b = f.readline()
print(b)
f.close()
5
2. 파일 입력
한 줄씩 읽어 오기 - for 구문 이용하기
f = open('about.txt', 'r')
for line in f:
print(line)
f.close()
6
2. 파일 입력
f = open('about.txt', 'r')
a = f.readlines()
print(a)
f.close()
7
2. 파일 입력
< 출력 결과 >
< 출력 결과 >
D = {}
with open('ban.txt') as f:
for line in f:
(key, val) = line.split()
D[int(key)] = val
for key, val in D.items():
print(key, val) 9
f.close()
2. 파일 입력
D = {}
f = open('ban_student.txt', 'r')
for line in f:
items = line.split()
key, values = items[0], items[1:]
D[key] = values
print(D) 10
3. 파일 출력
write() 예제
f = open("subject.txt", "w")
f.write('hello world')
f.write('python programming')
f.write('good bye')
f.close()
11
3. 파일 출력
writelines() 예제
f = open("subject2.txt", "w")
f.writelines(['hello\n','world\n','python\n',
'programming','good','bye'])
f.close()
12
기초 PYTHON 프로그래밍
20. 클래스와 객체
1. 객체 (object)
2. 클래스 (class)
3. 연산자 중복
4. 클래스와 모듈
1. 객체 (object)
>>> type(test)
<class 'function'>
>>> type(range)
<class 'type'>
>>> type(input)
<class 'builtin_function_or_method'>
>>> type(print)
<class 'builtin_function_or_method'>
3
2. 클래스
클래스 (class)
객체(object)를 만들기 위한 도구
클래스의 구성
def bark(self):
메소드 (method)
print(self.name, 'is barking')
5
2. 클래스
class Dog :
x = Dog('Jack', 3)
y = Dog('Daisy', 2)
x.bark()
y.bark()
print(x.name, 'is', x.age, 'years old.')
print(y.name, 'is', y.age, 'years old.')
6
2. 클래스
7
2. 클래스
list 클래스
>>> L1 = [1,3,5]
>>> dir(list)
>>> L2 = list([2,4,6])
['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', >>> L1.append(7)
'__imul__', '__init__', '__iter__', '__le__', '__len__',
>>> print(L1)
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', [1, 3, 5, 7]
'__rmul__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'clear', >>> L2.pop()
'copy', 'count', 'extend', 'index', 'insert', 'pop',
6
'remove', 'reverse', 'sort']
>>> print(L2)
[2, 4]
8
3. 연산자 중복
int 클래스
>>> dir(int) >>> x = 10
['__abs__', '__add__', '__and__', '__bool__', '__ceil__',
'__class__', '__delattr__', '__dir__', '__divmod__', >>> y = int(20)
'__doc__', '__eq__', '__float__', '__floor__',
'__floordiv__', '__format__', '__ge__', >>> z = x.__add__(y) # z = x + y
'__getattribute__', '__getnewargs__', '__gt__',
'__hash__', '__index__', '__init__', '__int__', >>> print(z)
'__invert__', '__le__', '__lshift__', '__lt__', '__mod__',
30
'__mul__', '__ne__', '__neg__', '__new__', '__or__',
'__pos__', '__pow__', '__radd__', '__rand__', >>> p,q,r = 100,100,200
'__rdivmod__', '__reduce__', '__reduce_ex__',
'__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', >>> p.__eq__(q) # p == q
'__rmul__', '__ror__', '__round__', '__rpow__',
'__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', True
'__rxor__', '__setattr__', '__sizeof__', '__str__',
'__sub__', '__subclasshook__', '__truediv__', >>> p.__gt__(r) #p>q
'__trunc__', '__xor__', 'bit_length', 'conjugate',
'denominator', 'from_bytes', 'imag', 'numerator', False
'real', 'to_bytes']
9
3. 연산자 중복
수치 연산자 메소드
메소드 연산자
__add__(self, other) +
__sub__(self, other) -
__mul__(self, other) *
__truediv__(self, other) /
__floordiv__(self, other) //
__mod__(self, other) %
__pow__(self, other[, modulo]) **
__gt__(self, other) >
__ge__(self, other) >=
__lt__(self, other) <
__le__(self, other) <=
__eq__(self, other) ==
10
__ne__(self, other) !=
3. 연산자 중복
class Point:
def __init__(self, x=0, y=0):
p1 = Point(2,3)
self.x = x
p2 = Point(4,7)
self.y = y
p3 = p1 + p2
print(p1.get())
def get(self):
print(p2.get())
return "(" + str(self.x) + "," + str(self.y) + ")"
print(p3.get())
def __add__(self, other):
newX = self.x + other.x
newY = self.y + other.y
return Point(newX, newY)
11
4. 클래스와 모듈
def show_color(self):
print(self.name, 'is', self.color)
pet.py 12