파이썬_기초문법_3

클래스를 만드는 목적!

  • 코드의 간결화!
    • 코드를 재사용!
  • 여러 라이브러리 –> 클래스로 구현이 됨
    • list 클래스, str 클래스
    • 객체로 사용
    • 변수명으로 정의!
  • 여러 클래스들이 모여서 하나의 라이브러리가 됨.
    • 장고 / 웹개발 / 머신러닝 / 시각화 / 데이터 전처리
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Person:     # 클래스 이름 첫문자는 대문자로 설정

#class attribute
country = "korean"

#instance attribute
def __init__(self, name, age): # def __init__(self, ) 는 디폴트로 정해진 부분이다
self.name = name
self.age = age

if __name__ == "__main__":
kim = Person("Kim", 100)
Lee = Person("lee", 100)

# access class attribute
print("kim은 {}".format(kim.__class__.country))
print("Lee는 {}".format(Lee.__class__.country))
kim은 korean
Lee은 korean

instance 메서드 생성

  • list.append(), list.extend()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Person:     


country = "korean"


def __init__(self, name, age):
self.name = name
self.age = age

# instance method 정의
def singing(self, songtitle, sales):
return "{}판매량 {}된 {}을 노래합니다.".format(self.name, sales, songtitle)

if __name__ == "__main__":
kim = Person("Kim", 100)
Lee = Person("lee", 100)

# access class attribute
print("kim은 {}".format(kim.country))
print("Lee는 {}".format(Lee.__class__.country))

# call instance method
print(kim.singing("A", 10))
print(Lee.singing("B", 200))
kim은 korean
Lee는 korean
Kim판매량 10된 A을 노래합니다.
lee판매량 200된 B을 노래합니다.
1
2
3
name = "lee"
songtitle = "B"
print("{} {}을 노래합니다.".format(name, songtitle))
lee B을 노래합니다.

클래스 상속

  • 부모님 유산…
    • 부모님 집 (냉장고, 세탁기, TV, etc)
    • 사용은 같이 함
  • 본인, 돈을 모음
    • 개인 노트북 구매 ( 여러분 각자 방에 비치 )
    • 노트분은 본인 것이지만 추가 가전 제품을 구매해서 확장!
1
2
3
4
5
6
class Parent:
pass
class Child(Parent):
pass
if __name__ == "__main__":
kim_child = Child()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Parent:

# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age

def whoAmI(self):
print("I am Parent!!")

def singing(self, songtitle):
return "{}된 {}을 노래합니다.".format(self.name, songtitle)

def dancing(self):
return "{} 현재 춤을 춥니다.".format(self.name)

class Child(Parent): # 상속
def __init__(self, name, age):
#super() function # 상속 기능
super().__init__(name, age)
print("Child Class is ON")

def whoAmI(self):
print("I am child")

def studying(self):
print("I am Fast Runner")

if __name__ == "__main__":
child_kim = Child("kim", 15)
parent_kim = Parent("kim", 45)
print(child_kim.dancing())
print(child_kim.singing("연애"))
# print(child_kim.studying())
child_kim.whoAmI()
parent_kim.whoAmI()
Child Class is ON
kim 현재 춤을 춥니다.
kim된 연애을 노래합니다.
I am Fast Runner
None
I am child
I am Parent!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class TV:

#init constructor ( 생성자 )
def __init__(self):
self.__maxprice = 500 # 클래스 내부에서 쓸 수 있게끔 private variable

def sell(self):
print("selling Price : {}".format(self.__maxprice))

def setMaxPrice(self, price):
self.__maxprice = price

if __name__ == "__main__":
tv = TV()
tv.sell()

# change price
# 안 바뀌는 코드의 예시
tv.__maxprice = 1000
tv.sell()

# setMaxPrice
# 값을 바꿀 수 있다?? 외부의 입력값을 업데이트 할 수 있다.
tv.setMaxPrice(1000)
tv.sell()
selling Price : 500
selling Price : 500
selling Price : 1000

자식 클래스가 많이 있는 라이브러리는 사용자가 스기 까다로울 것 같은데, 많이 써주는 이유는 자식클래스 이름마다 의미를 주려고 그런건가요?

  • 특수 목적을 해결하기 위해서 라이브러리를 만듦
  • 초기 버전은 3개 클래스 정도 만들면 해결이 되겠지?
    • 버그 나오고, 이슈 터지고 –> 개발자들이 해결
  • 2개 더 만들고 다시 배포

클래스 내부에 조건문

  • init contsructor에 조건문을 써보자!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Employee:

#init constructor
#name, salary
def __init__(self, name, salary = 0):
self.name = name

#조건문 추가
if salary > 0:
self.salary = salary
else:
self.salary = 0
print("급여는 0원이 될 수 없습니다. 다시 입력해십시오!!")

def update_salary(self, amount):
self.salary += amount

def weekly_salary(self):
return self.salary / 7

if __name__ == "__main__":
emp01 = Employee("Evan", -5000)
print(emp01.name)
print(emp01.salary)

emp01.salary = emp01.salary + 1500
print(emp01.salary)

emp01.update_salary(3000)
print(emp01.salary)

week_salary = emp01.weekly_salary()
print(week_salary)
급여는 0원이 될 수 없습니다. 다시 입력해십시오!!
Evan
0
1500
4500
642.8571428571429

클래스 Doctring

  • 문서화
  • 문서화의 일반적인 과정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Person:
"""
사람을 표현하는 클래스
...

Attributes
----------
name : str
name of the person

age : int
age of the person
...
...

Methods
----------

info(additional=""):
prints the person's name and age
"""
def __init__(self, name, age):
"""
Constructs all the neccessary attributes for the person object

Parameters
----------
name : str
name of the person

age : int
age of the person
"""

self.name = name
self.age = age

def info(self, additional=None):
"""
귀찮음...

Parameters
----------
additional : str, optional
more info to be displayed (Default is None)

Returns
-------
None
"""

print(f'My name is {self.name}. i am {self.age} years old.' + additional)

if __name__ == "__main__":
person = Person("Evan", age = 20)
person.info("나의 직장은 00이야")
help(Person)
My name is Evan. i am 20 years old.나의 직장은 00이야
Help on class Person in module __main__:

class Person(builtins.object)
 |  Person(name, age)
 |  
 |  사람을 표현하는 클래스
 |  ...
 |  
 |  Attributes
 |  ----------
 |  name : str
 |    name of the person
 |  
 |  age : int
 |    age of the person
 |  ...
 |  ...
 |  
 |  Methods
 |  ----------
 |  
 |  info(additional=""):
 |    prints the person's name and age
 |  
 |  Methods defined here:
 |  
 |  __init__(self, name, age)
 |      Constructs all the neccessary attributes for the person object
 |      
 |      Parameters
 |      ----------
 |      name : str
 |        name of the person
 |      
 |      age : int
 |        age of the person
 |  
 |  info(self, additional=None)
 |      귀찮음...
 |      
 |      Parameters
 |      ----------
 |        additional : str, optional
 |          more info to be displayed (Default is None)
 |      
 |      Returns
 |      -------
 |        None
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  person = <__main__.Person object>

클래스 실습

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 더하기, 빼기 기능이 있는 클래스
class Calculator:
def __init__(self):
self.result = 0

def add(self,num):
self.result += num
return self.result

def sub(self,num):
self.result -= num
return self.result

cal1 = Calculator()
cal2 = Calculator()

print(cal1.add(3))
print(cal1.add(4))
print(cal2.add(3))
print(cal2.add(7))
3
7
3
10
1
2
3
4
5
6
7
8
9
10
11
12
13
# 4칙연산 기능이 달린 클래스 정의
# 일단 더하기만 구현
class FourCal:
def setdata(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result

a = FourCal()
a.setdata(4,2)
a.add()
6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 4칙연산 기능이 달린 클래스 정의
class FourCal:
def setdata(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result

a = FourCal()
a.setdata(4,2)

print(a.mul())
print(a.sub())
print(a.div())
8
2
2.0

생성자

  • 위 함수의 setdata는 생성자의 역할을 한다.
  • setdata를 생성자 __init__으로 바꿔도 정상 작동한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# setdata를 생성자 __init__으로 변경
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result

a = FourCal(4, 2) # 이전과 달리 매개변수도 작성해야 작동.
print(a.mul())
print(a.sub())
print(a.div())
8
2
2.0

클래스의 상속

  • FourCal 클래스는 만들어 놓았으므로 FourCal 클래스를 상속하는 MoreFourCal 클래스는 다음과 같이 간단하게 만들 수 있다.
1
2
3
4
5
6
# 상속
class MoreFourCal(FourCal):
pass

a = MoreFourCal(4,2)
a.add()
6

python_numpy_01

라이브러리

  • 여러가지 라이브러리를 사용해보자

Numpy

Q : what is numpy?

A : 배열 연산이다.

Q : why numpy?

A : 두개의 리스트 연산 시도 → Type Error → Numpy 도입

1
2
3
4
5
# 다음 코드는 사용 시 error가 나온다.
A = [1, 2, 3]
B = [4, 5, 6]

A / B ** 2
1
2
3
4
5
6
7
8
9
# numpy 사용 시 정상적으로 작동한다.
import numpy as np

A = [1, 2, 3]
B = [4 ,5, 6]

np_A = np.array(A)
np_B = np.array(B)
np_A / np_B ** 2
array([0.0625    , 0.08      , 0.08333333])

Reshape

사용 예시

  • (2,3) 배열 -> np.reshape(3,2) -> (3,2)배열

사용 예시

  • np.reshape(-1, 2)에서 -1의 의미
    : 특정 차원에서 열은 2로 고정된 상태에서 행은 사이즈에 맞도록 자동으로 정렬해준다는 뜻
1
2
3
4
5
6
import numpy as np
temp_arr = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
temp_arr

new_arr = temp_arr.reshape(2, -1)
new_arr
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16]])
1
2
3
# -1을 이용한 자동 정렬
new_arr = temp_arr.reshape(4, -1)
new_arr
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])

조언

  • 머신러닝 / 딥러닝
    • 수학을 잘 하는 사람 vs 수학을 처음 하는 사람
    • 머신러닝 / 딥러닝 (인간이 만든 수식!)
    • 개념을 이해하고, 수식으로 이해하고, 코드로 그 수식을 구현해야
    • 머신러닝과 딥러닝을 쓰기 위해서는 수학자만 해야되냐!?
    • 결론은 아닙니다!
    • 머신러닝 / 딥러닝의 주 목적이 인간 생활의 보편적인 무제 해결을 위해 나온 것
    • 프레임워크로 형태로 내놨어요 (개념을 이해하고 있자!)
      • 개념만 문자열 타입으로 매개변수를 잘 조정만 하면 모델 만들어짐!
    • 성과를 내야 하는데 (개발자는 배포를 잘해야 함!)
      • 이미지 인식 모델을 만듬 / (쓸데가 없음…) / 안드로이드 앱 / 웹앱에 탑재할줄만 알아도
      • 기획 (어떤 문데를 풀까?)
    • AutoML
      • 코드를 4 ~ 5줄 치면 머신러닝 모델이 만들어짐!
      • 하지만 이공계 출신이라면 수식도 나름대로 정리해 볼 것

라이브러리 설치 방법 (vs R)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# R install.packages("패키지명")
# 파이썬 라이브러리 설치 코드에서 실행 (X)
# 터미널에서 설치

# 방법1. conda 설치
# --> 아나콘다 설치 후, conda 설치 (데이터 과학)
# conda 라이브러리 관리 (버전 업데이트가 조금 느림)

# 방법2. pip 설치
# --> 아나콘다 설치 안 함 / 파이썬만 설치

# git bash 열고, pip install numpy
#pip install numpy
# google colab에선 기본적 환경이 갖추어져 있음.

Numpy 라이브 불러오기

1
2
3
# 다음과 같이 np 라고 줄여서 출력한다.
import numpy as np
print(np.__version__)
1.21.5

배열로 변환

  • 1부터 10까지의 리스트를 만든다.
  • Numpy 배열로 변환해서 저장한다.
1
2
3
4
temp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = np.array(temp)
print(arr)
print(temp)
[ 1  2  3  4  5  6  7  8  9 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1
2
print(type(arr))
print(type(temp))
<class 'numpy.ndarray'>
<class 'list'>
  • Numpy를 사용하여 기초 통계 함수를 사용한다.
1
2
3
4
print(np.mean(arr))
print(np.sum(arr))
print(np.median(arr))
print(np.std(arr))
5.5
55
5.5
2.8722813232690143

사칙연산

1
2
3
4
5
math_scores = [90,80, 88]
english_scores = [80, 70, 90]

total_scores = math_scores + english_scores
total_scores
[90, 80, 88, 80, 70, 90]
1
2
3
4
5
6
7
8
math_scores = [90,80, 88]
english_scores = [80, 70, 90]

math_arr = np.array(math_scores)
english_arr = np.array(english_scores)

total_scores = math_arr + english_arr
total_scores
array([170, 150, 178])
1
np.min(total_scores)
150
1
np.max(total_scores)
178
1
2
3
4
5
6
7
8
9
10
11
12
math_scores = [2, 3, 4]
english_scores = [1, 2, 3]

math_arr = np.array(math_scores)
english_arr = np.array(english_scores)

#사칙연산
print("덧셈 : ", np.add(math_arr, english_arr))
print("뺄셈 : ", np.subtract(math_arr, english_arr))
print("곱셈 : ", np.multiply(math_arr, english_arr))
print("나눗셈 : ", np.divide(math_arr, english_arr))
print("거듭제곱 : ", np.power(math_arr, english_arr))
덧셈 :  [3 5 7]
뺄셈 :  [1 1 1]
곱셈 :  [ 2  6 12]
나눗셈 :  [2.         1.5        1.33333333]
거듭제곱 :  [ 2  9 64]

배열의 생성

  • 0차원부터 3차원까지 생성하는 방법
1
2
3
4
temp_arr = np.array(20)
print(temp_arr)
print(type(temp_arr))
print(temp_arr.shape)
20
<class 'numpy.ndarray'>
()
1
2
3
4
5
6
# 1차원 배열
temp_arr = np.array([1,2,3])
print(temp_arr)
print(type(temp_arr))
print(temp_arr.shape) # 배열의 형태 확인용
print(temp_arr.ndim) # ndim은 차원 확인용
[1 2 3]
<class 'numpy.ndarray'>
(3,)
1
1
2
3
4
5
6
# 2차원 배열
temp_arr = np.array([[1,2,3], [4, 5, 6]])
print(temp_arr)
print(type(temp_arr))
print(temp_arr.shape)
print(temp_arr.ndim) # ndim 은 차원 확인
[[1 2 3]
 [4 5 6]]
<class 'numpy.ndarray'>
(2, 3)
2
1
2
3
4
5
6
# 3차원 배열
temp_arr = np.array([[[1,2,3], [4, 5, 6]], [[1,2,3], [4, 5, 6]]])
print(temp_arr)
print(type(temp_arr))
print(temp_arr.shape)
print(temp_arr.ndim) # ndim 은 차원 확인
[[[1 2 3]
  [4 5 6]]

 [[1 2 3]
  [4 5 6]]]
<class 'numpy.ndarray'>
(2, 2, 3)
3
1
2
3
4
5
temp_arr = np.array([1, 2, 3, 4], ndmin = 2) # 차원을 변경 가능
print(temp_arr)
print(type(temp_arr))
print(temp_arr.shape)
print(temp_arr.ndim)
[[1 2 3 4]]
<class 'numpy.ndarray'>
(1, 4)
2

소수점 정렬

1
2
temp_arr = np.trunc([-1.23, 1.23])
temp_arr
array([-1.,  1.])
1
2
temp_arr = np.fix([-1.23, 1.23])
temp_arr
array([-1.,  1.])
1
2
3
# 반올림
temp_arr = np.around([-1.63789, 1.23784], 4) # 소수점 아래 4번째자리로 반올림 한다는 표현
temp_arr
array([-1.6379,  1.2378])
1
2
3
# 올림
temp_arr = np.floor([-1.63789, 1.23784])
temp_arr
array([-2.,  1.])
1
2
3
# 내림
temp_arr = np.ceil([-1.63789, 1.23784])
temp_arr
array([-1.,  2.])
  • shape 높이 * 세로 * 가로 순인건가요?
  • axis 축 설정

배열을 사용하는 다양한 방법들

1
2
3
# np.arange(5) -> 0 부터 시작하는 5개의 배열 생성
temp_arr = np.arange(5)
temp_arr
array([0, 1, 2, 3, 4])
1
2
3
# np.arange(1, 11, 3) -> 1 부터 11까지 3만큼 차이나게 배열 생성
temp_arr = np.arange(1, 11, 3)
temp_arr
array([ 1,  4,  7, 10])
1
2
3
4
5
6
7
# np.zeros -> 0으로 채운 배열 만들기
zero_arr = np.zeros((2,3))
print(zero_arr)
print(type(zero_arr))
print(zero_arr.shape)
print(zero_arr.ndim)
print(zero_arr.dtype) # dype = data type
[[0. 0. 0.]
 [0. 0. 0.]]
<class 'numpy.ndarray'>
(2, 3)
2
float64
1
2
3
4
5
6
7
# np.ones -> 1로 채운 배열 만들기
temp_arr = np.ones((4,5), dtype="int32")
print(temp_arr)
print(type(temp_arr))
print(temp_arr.shape)
print(temp_arr.ndim)
print(temp_arr.dtype)
[[1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]
 [1 1 1 1 1]]
<class 'numpy.ndarray'>
(4, 5)
2
int32
1
2
3
4
5
6
temp_arr = np.ones((2,6), dtype="int32")  
print(temp_arr)
print(type(temp_arr))
print(temp_arr.shape)
print(temp_arr.ndim)
print(temp_arr.dtype)
[[1 1 1 1 1 1]
 [1 1 1 1 1 1]]
<class 'numpy.ndarray'>
(2, 6)
2
int32
1
2
3
4
5
6
7
8
# reshape() 사용하여 배열 변환하기 
temp_arr = np.ones((12,12), dtype="int32")
temp_res_arr = temp_arr.reshape(4, -1) # -1 은 자동정령
print(temp_res_arr)
print(type(temp_res_arr))
print(temp_res_arr.shape)
print(temp_res_arr.ndim)
print(temp_res_arr.dtype)
[[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]]
<class 'numpy.ndarray'>
(4, 36)
2
int32

numpy 조건식

  • where(a, b, c) 사용법
    • a조건 True면 b로 변환, False이면 c로 변환
1
2
temp_arr = np.arange(10)
temp_arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
1
2
3
4
5
# 5보다 작은 값은 원래값으로 변환
# 5보다 큰 값은 원래 값 * 10
np.where(temp_arr <5, temp_arr, temp_arr * 10)

# where(a, b, c) a조건 True면 b로 변환, False이면 c로 변환
array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])
1
2
3
4
5
# 0~100 까지의 배열 만들고, 50보다 작은 값은 곱하기 10, 나머지는 그냥 원래 값으로 반환
temp_arr = np.arange(101)
temp_arr

np.where(temp_arr <50, temp_arr * 10, temp_arr)
array([  0,  10,  20,  30,  40,  50,  60,  70,  80,  90, 100, 110, 120,
       130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250,
       260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380,
       390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490,  50,  51,
        52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,  64,
        65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,
        78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,
        91,  92,  93,  94,  95,  96,  97,  98,  99, 100])

두가지 조건식을 사용해야 할 경우

  • np.select
  • 사용법은 다음 코드를 참고
1
2
3
4
5
6
7
temp_arr = np.arange(10)
temp_arr

# 5보다 큰 값은 곱하기 2, 2보다 작은 값은 더하기 100
condlist = [temp_arr > 5, temp_arr <2] # 조건식
choielist = [temp_arr *2, temp_arr + 100] # 같은 위치의 조건 만족 시, 설정한 대로 변환
np.select(condlist, choielist, default = temp_arr)
array([100, 101,   2,   3,   4,   5,  12,  14,  16,  18])

브로드캐스팅

  • 서로 다른 크기의 배열을 계산할 때 참고해야하는 내용이다.

파이썬_기초문법_2

기초 문법 리뷰

1
2
3
4
5
6
7
8
9
10
11
# 리스트
book_list = ["A", "B", "C"]
# append, extend, insert, remove, pop, etc

# 튜플
book_tuple = ("A", "B", "C")
# 수정 삭제가 불가능하다

# 딕셔너리
book_dictionary = {"책 제목" : ["A", "B"], "출판년도" : [2011, 2002]}
# keys(), values(), items(), get()

조건문 & 반복문

1
2
3
4
5
6
if True:
print("코드 실행")
elif True:
print("코드 실행")
else:
print("코드 실행")
1
2
for idx in range(3):
print(idx+1, "안녕하세요")
1 안녕하세요
2 안녕하세요
3 안녕하세요
1
2
3
book_list = ["프로그래밍 R", "혼자 공부하는 머신러닝"]
for book in book_list:
print(book)
프로그래밍 R
혼자 공부하는 머신러닝
1
2
3
strings01 = "Hello world"
for char in strings01:
print(char)
1
2
3
num_tuple = (1, 2, 3, 4)
for num in num_tuple:
print(num)
1
2
3
4
1
2
3
4
num_dict = {"A" : 1, "B" : 2}
for num in num_dict:
print(num)
print(num_dict[num])
A
1
B
2

반복문의 필요성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
product_name = ["요구르트", "우유", "과자"]
prices = [1000, 1500, 2000]
quantities = [5, 3, 4]

name = product_name[0]
sales = prices[0] * quantities[0]
print(name + "의 매출액은 " + str(sales) + "원이다.")

name = product_name[1]
sales = prices[1] * quantities[1]
print(name + "의 매출액은 " + str(sales) + "원이다.")

# 위 코드의 반복문 코드 작성 필요 절감

for num in range(len(product_name)):
name = product_name[num]
sales = prices[num] * quantities[num]
print(name + "의 매출액은 " + str(sales) + "원이다.")
요구르트의 매출액은 5000원이다.
우유의 매출액은 4500원이다.
요구르트의 매출액은 5000원이다.
우유의 매출액은 4500원이다.
과자의 매출액은 8000원이다.

while

  • 조건식이 들어간 반복문
    (vs for-loop 범위!!!)
1
2
3
4
5
6
count = 1
while count < 5:
count = count + 1
print("안녕하세요..")

print("5 초과했군요..")
안녕하세요..
안녕하세요..
안녕하세요..
안녕하세요..
5 초과했군요..
1
2
3
4
5
6
7
count = 3
while count > 0:
print("안녕하세요..")
count = count - 1
print(count)

print("0 미만이군요..")
안녕하세요..
2
안녕하세요..
1
안녕하세요..
0
0 미만이군요..
  • 개발자를 지향한다!
    • while 공부 좀 더 비중 있게 다루는 걸 추천
  • 데이터 분석
    • for-loop 공부를 좀 더 비중있게 하는 것 추천

사용자 정의 함수 (User-Defined Function)

  • why?

클래스(Class)를 왜 쓸까?

  • 코드의 반복성을 줄이기 위해서 사용!

len() –> 누군가가 만들었고, 우리는 그걸 그냥 쓰는 것

  • 리스트의 길이 구할 때 사용
  • 리스트 전체 길이를 구하겠다!? –> 1회성? 나만 쓰는가? no
1
2
3
4
5
def 함수명():
#코드 실행
return

함수명()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def add(a, b):
"""정수 2개를 입력받아 더하는 함수입니다.

Args:
a(int) : 계산할 정수
b(int) : 계산할 정수
c(int) : 계산 결과

Returns:
int
"""
c = a + b
return c
add(1,2)


def minus(a,b):
"""정수 2개를 입력받아 빼는 함수입니다.

Args:
a(int) : 계산할 정수
b(int) : 계산할 정수
c(int) : 계산 결과

Returns:
int
"""
c = a - b
return c
minus(10, 5)


def multiple(a,b):
"""정수 2개를 입력받아 곱하는 함수입니다.

Args:
a(int) : 계산할 정수
b(int) : 계산할 정수
c(int) : 계산 결과

Returns:
int
"""
c = a * b
return c
multiple(10,5)


def divide(a,b):
"""정수 2개를 입력받아 나누는 함수입니다.

Args:
a(int) : 계산할 정수
b(int) : 계산할 정수
c(float) : 계산 결과

Returns:
float
"""
c = a / b
return c
divide(10,5)

if __name__ == "__main__":
print("add(10,5) = ", add(10,5) )
print("minus(10,5) = ", minus(10,5) )
print("multiple(10,5) = ", multiple(10,5) )
print("divide(10,5) = ", divide(10,5) )
add(10,5) =  15
minus(10,5) =  5
multiple(10,5) =  50
divide(10,5) =  2.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

def minus(a,b):
"""정수 2개를 입력받아 빼는 함수입니다.

Args:
a(int) : 계산할 정수
b(int) : 계산할 정수
c(int) : 계산 결과

Returns:
int
"""
c = a - b
return c
minus(10, 5)

jupyter notebook, ipynb 파일명

.py로 저장(PyCharm..)

1
!which pyhon

basic.py로 저장할 때, 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# /usr/local/bin/python
# -*- coding: utf-8 -*-

def temp(content, letter):
"""content 안에 있는 문자를 세는 함수입니다.

Args:
content(str) : 탐색 문자열
letter(str) : 찾을 문자열

Returns:
int
"""
print("함수 테스트")

cnt = len([char for char in content if char == letter])
return cnt

if __name__ == "__main__":
help(temp)
docstring = temp.__doc__
print(docstring)
Help on function temp in module __main__:

temp(content, letter)
    content 안에 있는 문자를 세는 함수입니다.
    
    Args:
      content(str) : 탐색 문자열
      letter(str) : 찾을 문자열
    
    Returns:
      int

content 안에 있는 문자를 세는 함수입니다.

  Args:
    content(str) : 탐색 문자열
    letter(str) : 찾을 문자열

  Returns:
    int
  

help()

  • 위 코드에서 help()는 본인이 작성한 주석을 바탕으로 문서화한다.

리스트 컴프리헨션

  • for-loop 반복문을 한 줄로 처리
  • 리스트 안에 반복문을 작성할 수 있다
1
2
3
4
5
6
7
8
9
10
11
12
13
my_list = [[10], [20,30]]
print(my_list)

flattened_list = []
for value_list in my_list:
print(value_list)
for value in value_list:
print(value)
flattened_list.append(value)

print(flattened_list)

# 결괏값 : return[10 ,20, 30]
[[10], [20, 30]]
[10]
10
[20, 30]
20
30
[10, 20, 30]
1
2
3
my_list = [[10], [20, 30]]
flattened_list = [value for value_list in my_list for value in value_list] # 리스트 컴프리헨션
print(flattened_list)
[10, 20, 30]
1
2
3
4
letters = []
for char in "helloworld":
letters.append(char)
print(letters)
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
1
2
letters2 = [char for char in "helloworld"]  # 리스트 컴프리헨션
print(letters)
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
1
2
3
4
5
6
7
8
9
value_list = [1, 2, 3, 4, 5, 6]
print("avg: ", sum(value_list) / len(value_list))
# 중간값

midpoint = int(len(value_list) / 2)
#len(value_list) % 2 == 0;
print((value_list[midpoint -1 ] + value_list[midpoint]) / 2)
print(value_list[midpoint])

avg:  3.5
3.5
4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 사용자 정의함수의 문서화
def mean_and_median(value_list):
""" 숫자 리스트의 요소들의 평균과 중간값을 구하는 코드를 작성해라
Args:
value_list (iterable of int / float) : A list of int numbers

Returns:
tuple(float, float)
"""
#평균
mean = sum(value_list) / len(value_list)

#중간값
midpoint = int(len(value_list) / 2)
if len(value_list) % 2 == 0:
median = (value_list[midpoint - 1] + value_list[midpoint]) / 2
else:
median = value_list[midpoint]

return mean, median

if __name__ == "__main__":
value_list = [1, 1, 2, 2, 3, 4, 5]
avg, median = mean_and_median(value_list)
print("avg : ", avg)
print("median", median)
avg :  2.5714285714285716
median 2
  • 데코레이터, 변수명 immutable or mutable, context manager는
    jump to python 페이지에 없기에 따로 찾아 공부해야 한다.

함수 실습

여러 개의 입력값을 받는 함수

1
2
3
4
5
6
7
# 여러 개의 입력값을 받는 함수 만들기
def add_many(*args):
result = 0
for i in args:
result = result + i
return result

1
2
3
4
5
6
7
# 위 함수를 이용해보자
result = add_many(1,2,3)
print(result)

#위 함수는 매개변수가 몇 개든 작동한다.
result = add_many(1,2,3,4,5,6,7,8,9,10)
print(result)
6
55
1
2
3
4
5
6
7
8
9
10
11
# 여러 개의 입력값을 받는 함수 만들기2
def add_mul(choice, *args):
if choice == "add":
result=0
for i in args:
result = result + i
elif choice == "mul":
result = 1
for i in args:
result = result * i
return result
1
2
3
4
5
6
# 위 함수를 이용해보자
result = add_mul('add', 1, 2, 3, 4, 5)
print(result)

result = add_mul('mul', 1, 2, 3, 4, 5)
print(result)
15
120

키워드 파라미터 kwargs

  • 키워드 파라미터를 사용할 때는 매개변수 앞에 별 두 개(**)를 붙인다.
1
2
3
4
5
6
7
8
9
10
# 매개변수 kwargs를 출력하는 함수이다.
def print_kwargs(**kwargs):
print(kwargs)

# 위 함수를 사용해보자
print_kwargs(a=1)
print_kwargs(name='foo', age=3)
{'age': 3, 'name': 'foo'}

# **을 붙이면 매개변수 kwargs는 딕셔너리가 되고 모든 key=value 형태의 결괏값이 그 딕셔너리에 저장된다.
{'a': 1}
{'name': 'foo', 'age': 3}





{'age': 3, 'name': 'foo'}

매개변수에 초깃값 미리 설정하기

1
2
3
4
5
6
7
8
9
10
11
def say_myself(name, old, man=True):    # boolean 값을 이용하여 설정
print("나의 이름은 %s 입니다." % name)
print("나이는 %d살입니다." % old)
if man :
print("남자입니다.") # True
else :
print("여자입니다.") # False

say_myself("박응용", 27)
say_myself("박응용", 27, True)
say_myself("박응용", 27, False)
나의 이름은 박응용 입니다.
나이는 27살입니다.
남자입니다.
나의 이름은 박응용 입니다.
나이는 27살입니다.
남자입니다.
나의 이름은 박응용 입니다.
나이는 27살입니다.
여자입니다.

함수 안에서 선언한 변수의 효력 범위

1
2
3
4
5
6
7
8
9
a = 1
def vartest(a):
a = a +1

vartest(a)
print(a)

# 결과 = 1
# 즉 함수 안에서 사용하는 매개변수는 함수 밖의 변수 이름과는 전혀 상관이 없다는 뜻이다.
1

함수 안에서 함수 밖의 변수를 변경하는 방법

    1. return 사용하기
    1. global 사용하기
1
2
3
4
5
6
7
8
# return 사용하기
a = 1
def vartest(a):
a = a + 1
return a # return으로 값 반환

a = vartest(a)
print(a)
2
1
2
3
4
5
6
7
8
# global 사용하기
a = 1
def vartest():
global a
a = a + 1

vartest() #효과는 있지만, 가급적 사용하지 말자.
print(a)
2

lambda

  • 함수를 생성할 때 사용하는 예약어로 def와 동일한 역할을 한다.
  • 보통 함수를 한줄로 간결하게 만들 때 사용
1
2
3
add = lambda a, b : a+b
result = add(3,4)
print(result)
7

사용자 입력과 출력

사용자 입력

  • input 사용
1
2
3
4
5
6
number1 = input("숫자를 입력하세요... : ")
print(number1) # 문자열 취급이므로 주의

number2 = int(input("숫자를 입력하세요... : "))
print(number2) # int로 형변환하여 정수 취급됨.

숫자를 입력하세요... : 1
1
숫자를 입력하세요... : 4
4
1
2
3
# 큰따옴표로 둘러싸인 문자열은 + 연산과 동일하다
print("life" "is" "too short")
print("life" + "is" + "too short")
lifeistoo short
lifeistoo short
1
2
# 문자열 띄어쓰기는 콤마로 한다
print("life", "is", "too short")
life is too short
1
2
3
4
# 한 줄에 결괏값 출력하기
for i in range(10):
print(i, end=' ')
# 매개변수 end를 사용하여 끝 문자를 지정
0 1 2 3 4 5 6 7 8 9 

파일 생성하기

  • 파일 열기 모드에는 다음과 같은 것이 있다.
    • r : 읽기모드 - 파일을 읽기만 할 때 사용
    • w : 쓰기모드 - 파일에 내용을 쓸 때 사용
    • a : 추가모드 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용
1
2
f = open("새파일.txt", 'w')
f.close()
1
2
3
# 만약 새파일.txt 파일을 C:/doit 디렉터리에 생성하고 싶다면 다음과 같이 작성
f = open("C:/doit/새파일.txt", 'w')
f.close()
1
2
3
4
5
6
# 파일을 쓰기 모드로 열어 출력값 적기
f = open("C:/doit/새파일.txt", 'w')
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
1
2
3
4
5
6
# 파일에 새로운 내용 추가하기
f = open("C:/doit/새파일.txt",'a')
for i in range(11, 20):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()

4장 연습문제

1
2
3
4
5
6
7
8
9
10
# Q1 주어진 자연수가 홀수인지 짝수인지 판별해 주는 함수(is_odd)를 작성해 보자.

def is_odd(n):
if n%2 ==0 :
print("짝수입니다...")
else :
print("홀수입니다...")

num = int(input("자연수를 입력하세요...: "))
is_odd(num)
자연수를 입력하세요...: 3
홀수입니다...
1
2
3
4
5
6
7
8
9
10
11
# Q2 입력으로 들어오는 모든 수의 평균 값을 계산해 주는 함수를 작성해 보자. 
# (단 입력으로 들어오는 수의 개수는 정해져 있지 않다.)

def cal_median(*args):
result = 0
for i in args:
result = result + i
return result / len(args)

result = cal_median(1,2,3,4,5,6,7,8,9,10)
print(result)
5.5
1
2
3
4
5
6
7
8
9
# Q3 다음은 두 개의 숫자를 입력받아 더하여 돌려주는 프로그램이다.
# 3과 6을 입력했을 때 9가 아닌 36이라는 결괏값을 돌려주었다. 이 프로그램의 오류를 수정해 보자.

input1 = int(input("첫번째 숫자를 입력하세요:"))
input2 = int(input("두번째 숫자를 입력하세요:"))
# int를 통한 형변환을 시행.

total = input1 + input2
print("두 수의 합은 %s 입니다" % total)
첫번째 숫자를 입력하세요:1
두번째 숫자를 입력하세요:4
두 수의 합은 5 입니다
1
2
3
4
5
6
# Q4 다음 중 출력 결과가 다른 것 한 개를 골라 보자.

print("you" "need" "python")
print("you"+"need"+"python")
print("you", "need", "python") # 콤마를 이요한 띄어쓰기를 사용함
print("".join(["you", "need", "python"]))
youneedpython
youneedpython
you need python
youneedpython
1
2
3
4
5
6
7
8
9
10
# Q5 다음은 "test.txt"라는 파일에 "Life is too short" 문자열을 저장한 후 다시 그 파일을 읽어서 출력하는 프로그램이다. 
# 예상한 값을 출력할 수 있도록 프로그램을 수정해 보자.

f1 = open("test.txt", 'w')
f1.write("Life is too short")
f1.close() # 열린 파일 객체를 닫는다.

f2 = open("test.txt", 'r')
print(f2.read())
f2. close() # close를 추가함.
Life is too short
1
2
3
4
5
6
7
8
9
# Q6 사용자의 입력을 파일(test.txt)에 저장하는 프로그램을 작성해 보자. 
#(단 프로그램을 다시 실행하더라도 기존에 작성한 내용을 유지하고 새로 입력한 내용을 추가해야 한다.)
# 다시 풀어보자

user_input = input("저장할 내용을 입력하세요:")
f = open('test.txt', 'a') # 내용을 추가하기 위해서 'a'를 사용
f.write(user_input)
f.write("\n") # 입력된 내용을 줄 단위로 구분하기 위한 개행 문자 사용
f.close()
저장할 내용을 입력하세요:hihi
1
2
3
4
5
6
7
8
9
10
11
# Q7 다음과 같은 내용을 지닌 파일 test.txt가 있다.  이 파일의 내용 중 "java"라는 문자열을 "python"으로 바꾸어서 저장해 보자.
# 다시 풀어보자
f = open('test.txt', 'r')
body = f.read()
f.close()

body = body.replace('java', 'python')

f = open('test.txt', 'w')
f.write(body)
f.close()

파이썬_기초문법_1

Hello world

1
print("Hello, World")
Hello, World

주석 처리

  • 코드 작업 시, 특정 코드에 대해 설명
  • 사용자 정의 함수 작성 시, 클래스 작성시.. (도움말 작성..)
1
2
3
4
5
6
# 한 줄 주석 처리
'''
여러 줄 주석 처리 시
'''

print( "Hello, World!")
Hello, World!

변수 (Scalar)

  • 객체(Object)로 구현이 됨
    • 하나의 자료형(Type)을 가진다.
    • 클래스로 정의가 됨.
      • 다양한 함수들이 존재 함.

int

  • init 정수를 표현하는데 사용함.
1
2
3
4
5
6
7
8
9
#데이터 전처리..
#데이터 전처리를 잘해야! 분석도 잘함. 예측 모형도 잘 만듬.
#데이터 전처리를 잘하기 위해서는, 기초문법이 중요함.

num_int = 1
num_int2 = 3
print(num_int)
print(num_int2)
print(type(num_int))
1
3
<class 'int'>

float

  • 실수를 표현하는데 사용한다.
1
2
3
num_float = 0.2
print(num_float)
print(type(num_float))
0.2
<class 'float'>
1
2
## bool
- TrueFalse로 나타내는 Boolean 값을 표현하는데 사용한다.
1
2
3
bool_true = True
print(bool_true)
print(type(bool_true))
True
<class 'bool'>

None

  • Null을 나타내는 자료형으로 None이라는 한 가지 값만 가집니다.
1
2
3
none_x = None
print(none_x)
print(type(none_x))
None
<class 'NoneType'>

사칙연산

  • 정수형 사칙 연산
1
2
3
4
5
6
7
8
9
a = 10
b = 5
print('a + b = ', a+b)
print('a - b = ', a-b)
print('a * b = ', a*b)
print('a / b = ', a/b)
print('a // b = ', a//b)
print('a % b = ', a%b)
print('a ** b = ', a**b)
a + b =  15
a - b =  5
a * b =  50
a / b =  2.0
a // b =  2
a % b =  0
a ** b =  100000

실수형 사칙연산

1
2
3
4
5
6
7
8
9
a = 10.0
b = 5.0
print('a + b = ', a+b)
print('a - b = ', a-b)
print('a * b = ', a*b)
print('a / b = ', a/b)
print('a // b = ', a//b)
print('a % b = ', a%b)
print('a ** b = ', a**b)
a + b =  15.0
a - b =  5.0
a * b =  50.0
a / b =  2.0
a // b =  2.0
a % b =  0.0
a ** b =  100000.0

논리형 연산자

  • Bool 형은 True와 False 값으로 정의
  • AND / OR
1
2
3
4
5
6
7
8
9
10
11
12
x = 5 > 4  # True
y = 3 > 4 # False

print(x and x)
print(x and y)
print(y and x)
print(y and y)
print("-----")
print(x or x)
print(x or y)
print(y or x)
print(y or y)

비교 연산자

  • 부등호를 의미합니다.
  • 비교 연산자를 True와 False값을 도출

논리 & 비교 연산자 응용

1
2
var = input("입력해주세요....")
print(type(var)) # 숫자를 입력해도 str로 판단
입력해주세요....1
<class 'str'>
  • 형변환을 해준다.
  • 문자열, 정수, 실수 등등등
1
2
var = int("1")   # 형변환
print(type(var))
<class 'int'>
1
2
var = int(input("숫자를 입력하여 주세요 : "))  # 형변환
print(type(var))
숫자를 입력하여 주세요 : 1
<class 'int'>
1
2
3
4
5
6
7
8
9
num1 = int(input("숫자를 입력하여 주세요... : ")) # 10
num2 = int(input("숫자를 입력하여 주세요... : ")) # 3
num3 = int(input("숫자를 입력하여 주세요... : ")) # 5
num4 = int(input("숫자를 입력하여 주세요... : ")) # 7

var1 = num1 >= num2 # True
var2 = num3 < num4 # True
print(var1 and var2)
print(var1 or var2)
숫자를 입력하여 주세요... : 10
숫자를 입력하여 주세요... : 3
숫자를 입력하여 주세요... : 5
숫자를 입력하여 주세요... : 7
True
True

변수 ( Non Scalar)

  • 문자열을 입력
1
2
print("'Hello, world'")
print('"Hello, world"')
'Hello, world'
"Hello, world"

String 연산자

  • 덧셈 연산자를 써보자.
1
2
3
4
str1 = "Hello "
str2 = "World! "
str3 = "\n"
print(str1 + str2)
Hello World! 
  • 곱셈 연산자를 사용해본다.
1
2
greeting = str1 + str2 + str3
print(greeting * 3)
Hello World! 
Hello World! 
Hello World! 

indexing

  • 문자열 인덱싱은 각각의 문자열 안에서 범위를 지정하여 특정 문자를 추출한다.
1
2
greeting = "Hello kaggle!"
print(greeting[6])
k

슬라이싱

  • 범위를 지정하고 데이터를 가져온다.
1
2
3
4
5
6
7
greeting

print(greeting[:])
print(greeting[6:])
print(greeting[:6]) # 시작 인덱스 ~ 끝 인덱스-1 만큼 출력하므로 Hello
print(greeting[3:9])
print(greeting[0:9:2]) # 3번째 index는 몇번 건너띄는 것인지 표시
Hello kaggle!
kaggle!
Hello 
lo kag
Hlokg

리스트

  • 시퀀스 데이터 타입
  • 데이터에 순서가 존재하냐! 슬라이실이 가능해야 함.
  • 대관호 ([‘값1’, ‘값2’, ‘값3’])
1
2
3
4
5
6
7
8
9
10
11
a = []           # 빈 리스트
a_func = list() # 빈 리스트 생성
b = [1] # 숫자가 요소가 될 수 있다.
c = ['apple'] # 문자열도 요소가 될 수 있다.
d = [1, 2, ['apple']] # 리스트 안에 또 다른 리스트 요소를 넣을 수 있다.

print(a)
print(a_func)
print(b)
print(c)
print(d)
[]
[]
[1]
['apple']
[1, 2, ['apple']]

리스트 슬라이싱

1
2
3
4
5
6
7
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# print(a)
print(a[0])
print(a[6:])
print(a[:5])
print(a[3:5])
print(a[1:9:2])
1
[7, 8, 9, 10]
[1, 2, 3, 4, 5]
[4, 5]
[2, 4, 6, 8]
1
2
3
4
5
6
a = [["apple", "banana", "cherry"], 1]
print(a[0])
print(a[0][2])
print(a[0][0][4])
print(a[0][0][-1])
print(a[0][2][2])
['apple', 'banana', 'cherry']
cherry
e
e
e
1
2
3
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(a[::-1]) # 역순
print(a[::2])
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 3, 5, 7, 9]
1
2
3
4
5
6
## 리스트 연산자
a = ["john", "evan"]
b = ["alice", "eva"]

c = a + b
print(c)
['john', 'evan', 'alice', 'eva']
1
2
3
4
c = a * 3
d = b * 0
print("a * 3 = ", c)
print("b * 0 = ", d)
a * 3 =  ['john', 'evan', 'john', 'evan', 'john', 'evan']
b * 0 =  []

리스트 수정 및 삭제

1
2
3
a = [0, 1, 2]
a[1] = "b"
print(a)
[0, 'b', 2]

리스트 값 추가하기

1
2
3
4
5
6
7
8
9
a = [100, 200, 300]
a.append(400)
print(a)

a.append([500, 600])
print(a)

a.extend([500, 600]) # extend는 []없이 추가한다.
print(a)
[100, 200, 300, 400]
[100, 200, 300, 400, [500, 600]]
[100, 200, 300, 400, [500, 600], 500, 600]
1
2
3
4
a = [0, 1, 2]
# a.insert(인덱스번호, 넣고자하는 값)
a.insert(1,100)
print(a)
[0, 100, 1, 2]

리스트 값 삭제하기

1
2
3
4
5
a = [4, 3, 2, 1, "A"]
a.remove(1) # 리스트 안에 있는 값을 삭제
print(a)
a.remove("A")
print(a)
[4, 3, 2, 'A']
[4, 3, 2]
1
2
3
4
5
6
7
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

del a[1] # 인덱스 번호
print(a)

del a[1:5]
print(a)
[1, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 7, 8, 9, 10]
1
2
3
4
b = ["a", "b", "c", "d"]
x = b.pop() # 맨 끝자리 하나를 가져온다.
print(x)
print(b)
d
['a', 'b', 'c']

그 외 메서드

1
2
3
4
5
a = [0, 1, 2, 3]
print(a)

a.clear()
print(a)
[0, 1, 2, 3]
[]
1
2
3
a = ["a", "a", "b", "b"]
print(a.index("a")) # 해당 문자가 여럿 있을 경우, 처음 하나만 출력
print(a.index("b"))
0
2
1
2
3
4
5
6
7
8
9
a = [1, 4, 5, 2, 3]
b = [1, 4, 5, 2, 3]

a.sort()
print("sort() : ", a)

# 내림차순
b.sort(reverse=True)
print("sort(reverse=True) : ", b)
sort() :  [1, 2, 3, 4, 5]
sort(reverse=True) :  [5, 4, 3, 2, 1]

튜플

  • List와 비슷하다.
  • 슬라이싱, 인덱싱 등등
  • (vs 리스트) : 튜플은 수정 삭제가 안된다.
1
2
3
4
5
6
tuple1 = (0)  # 끝에 코마(,)를 붙이지 않을 때
tuple2 = (0, ) # 끝에 코마 붙일 때
tuple3 = 0, 1, 2
print(type(tuple1))
print(type(tuple2))
print(type(tuple3))
<class 'int'>
<class 'tuple'>
<class 'tuple'>
1
2
3
4
5
6
7
8
a = (0, 1, 2, 3, 'a')
print(type(a))

print(a)
b[1]="b"

a= tuple(b)
print(a)
<class 'tuple'>
(0, 1, 2, 3, 'a')
(5, 'b', 3, 2, 1)

튜플 인덱싱 및 슬라이싱 하기

1
2
3
4
a = (0, 1, 2, 3, 'a')
print(a[1])
print(a[2])
print(a[4])
1
2
a

더하기 곱셈 연산자 사용

1
2
3
4
5
6
t1 = (1, 2, 3)
t2 = (4, 5, 6)

print(t1 + t2)
print(t1 * 3)
print(t1 * 0)
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
()

딕셔너리

  • key & value 값으로 나뉨.
1
2
3
4
5
6
7
8
dict_01 = {'teacher' : 'evan',
'class' : 601,
'students' : 24,
'학생이름' : ['A', 'Z']}
dict_01
print(dict_01['teacher'])
print(dict_01['class'])
print(dict_01['학생이름'])
evan
601
['A', 'Z']
1
2
3
print(dict_01.keys())

print(list(dict_01.keys()))
dict_keys(['teacher', 'class', 'students', '학생이름'])
['teacher', 'class', 'students', '학생이름']
1
print(dict_01.values())
dict_values(['evan', 601, 24, ['A', 'Z']])
1
dict_01.items()
dict_items([('teacher', 'evan'), ('class', 601), ('students', 24), ('학생이름', ['A', 'Z'])])
1
2
3
4
print(dict_01.get("teacher"))   # get 메소드
print(dict_01.get("선생님", "값 없음"))
print(dict_01.get("class"))
print(dict_01.get("students"))
evan
값 없음
601
24

조건문 & 반복분

  • 일상에서 조건문 언제쓸까요?
1
2
3
4
5
6
7
# 날씨가 맑다 --> 우산을 안 책겨간다
# 날씨가 흐리다 -> 우산을 챙긴다
weather = "맑음"
if weather == "비":
print("우산을 가져간다")
else :
print("우산을 가져가지 않는다")
우산을 가져가지 않는다
1
2
3
4
5
6
7
8
9
# 등급표 만들기
# 60점 이상 합격 / 불합격
# 숫자는 아무거나 써도 상관없음

grade = 70
if grade > 60 :
print("합격입니다.")
else :
print("불합격입니다.")
합격입니다.
1
2
3
4
5
grade = int(input("숫자를 입력하여 주세요... : "))
if grade > 60 :
print("합격입니다.")
else :
print("불합격입니다.")
숫자를 입력하여 주세요... : 10
불합격입니다.
1
2
3
4
5
6
7
8
9
10
# 90점 이상은 A등급
# 80점 이상은 B등급
# 나머지는 F등급
grade = int(input("숫자를 입력하여 주세요... : "))
if grade >= 90 :
print("A 등급입니다.")
elif grade >= 80 :
print("B 등급입니다.")
else :
print("F 등급입니다.")
숫자를 입력하여 주세요... : 85
B 등급입니다.

반복문

for문

1
2
3
# 안녕하세요! 5번 반복하라
for i in range(5) :
print(i+1, "안녕하세요")
1 안녕하세요
2 안녕하세요
3 안녕하세요
4 안녕하세요
5 안녕하세요
1
2
3
4
5
6
7
8
9
10
count = range(5)
print(count)

for n in count:
print(str(n+1) + "번째")
if(n+1) == 3:
print("그만합니다")
break
print("축구 슈팅")

range(0, 5)
1번째
축구 슈팅
2번째
축구 슈팅
3번째
그만합니다
1
2
3
4
5
6
a = "hello"
for x in a :
if x in a :
if x == "l" :
break
print(x)
h
e

while문

반복해서 문장을 수행해야 할 경우 while문을 사용한다.

1
2
3
4
5
6
7
#열 번 찍어 안 넘어가는 나무 없다"
treehit = 0
while treehit < 10:
treehit = treehit + 1
print("나무를 %d번 찍었습니다." % treehit)
if treehit == 10:
print("나무가 넘어갑니다.")
나무를 1번 찍었습니다.
나무를 2번 찍었습니다.
나무를 3번 찍었습니다.
나무를 4번 찍었습니다.
나무를 5번 찍었습니다.
나무를 6번 찍었습니다.
나무를 7번 찍었습니다.
나무를 8번 찍었습니다.
나무를 9번 찍었습니다.
나무를 10번 찍었습니다.
나무 넘어갑니다.
1
2
3
4
5
6
7
# while문 만들기
prompt = """
1.Add
2.Del
3.List
4.Quit
Enter number: """
1
2
3
4
number = 0
while number != 4:
print(prompt)
number = int(input())
1.Add
2.Del
3.List
4.Quit
Enter number: 
4
1
2
3
4
5
6
7
8
9
10
# 커피 자판기 이야기
coffee = 10
money = 300
while money :
print("돈을 받았으니 커피를 줍니다.")
coffee = coffee - 1
print("남은 커피의 양은 %d개입니다." % coffee)
if coffee == 0:
print("커피가 다 떨어졌습니다. 판매를 중지합니다.")
break

while문의 맨 처음으로 돌아가기 (continue)

1
2
3
4
5
6
a = 0
while a < 10 :
a = a + 1
if a % 2 == 0 :
continue
print(a)
1
3
5
7
9

무한 루프

1
2
while True :
print("Ctrl+C를 눌러야 while문을 빠져나갈 수 있습니다.")

문자열 포매팅

  • 문자열 안의 특정한 값을 바꿔야 할 경우가 있을 때 이것을 가능하게 해주는 것이 바로 문자열 포매팅 기법이다.
  • 숫자는 %d, 문자는 %s
1
2
# 숫자 바로 대입 
"I eat %d apple." % 3
'I eat 3 apple.'
1
2
# 문자열 바로 대입
"I eat %s apples." % "five"
'I eat five apples.'
1
2
3
# 숫자 값을 나타내는 변수로 대입
number = 3
"I eat %d apples." % number
'I eat 3 apples.'
1
2
3
4
# 2개 이상의 값 넣기
number = 10
day = "three"
"I ate %d apples. so I was sick for %s day" % (number, day)
'I ate 10 apples. so I was sick for three day'
1
2
"I have %s apples" % 3
"rate is %s " % 3.234
'rate is 3.234 '

format 함수를 사용한 포매팅

  • 문자열의 format 함수를 사용하면 좀 더 발전된 스타일로 문자열 포맷을 지정할 수 있다.
1
2
# 숫자 바로 대입하기
"I eat {0} apples".format(3)
'I eat 3 apples'
1
2
# 문자 바로 대입하기
"I eat {0} apples".format("five")
'I eat five apples'
1
2
3
# 숫자 값을 가진 변수로 대입하기
number = 3
"I eat {0} apples".format(number)
'I eat 3 apples'
1
2
3
4
# 2개 이상의 값 넣기
number = 10
day = "three"
"I ate {0} apples. so I was sick for {1} days. ".format(number, day)
'I ate 10 apples. so I was sick for three days. '
1
2
# 이름으로 넣기
"I ate {number} apples. so I was sick for {day} days.".format(number=10, day=3)
'I ate 10 apples. so I was sick for 3 days.'
1
2
# 인덱스와 이름을 혼용해서 넣기
"I ate {0} apples. so I was sick for {day} days.".format(10, day=3)
'I ate 10 apples. so I was sick for 3 days.'
1
2
# 왼쪽 정렬
"{0:<10}".format("hi") # 왼쪽으로 정렬하고 총 자릿수를 10으로 설정.
'hi        '
1
2
# 오른쪽 정렬
"{0:>10}".format("hi") # 오른쪽으로 정렬하고 총 자릿수를 10으로 설정.
'        hi'
1
2
# 가운데 정렬
"{0:^10}".format("hi")
'    hi    '
1
2
3
# 공백 채우기
"{0:=^10}".format("hi")
"{0:!<10}".format("hi")
'hi!!!!!!!!'
1
2
3
# 소수점 표현하기
y = 3.42134234
"{0:0.4f}".format(y) # 소수점을 4자리까지만 표현
'3.4213'
1
2
# 정렬과 소수점 표현 
"{0:10.4f}".format(y)
'    3.4213'
1
2
# { 또는 } 문자 표현하기
"{{ and }}".format()
'{ and }'

f 문자열 포매팅

  • 파이썬 3.6 버전부터는 f 문자열 포매팅 기능을 사용할 수 있다.
  • f 문자열 포매팅은 표현식을 지원한다.
  • 표현식이란 문자열 안에서 변수와 +, -와 같은 수식을 함께 사용하는 것을 말한다.
1
2
3
name = '홍길동'
age = 30
f'나의 이름은 {name}입니다. 나이는 {age}입니다.'
'나의 이름은 홍길동입니다. 나이는 30입니다.'
1
2
age = 30
f'나는 내년이면 {age+1}살이 된다.'
'나는 내년이면 31살이 된다.'
1
2
3
# f 문자열 포매팅에서의 딕셔너리
d = {'name':'홍길동', 'age':30}
f'나의 이름은 {d["name"]}입니다. 나이는 {d["age"]}입니다.'
'나의 이름은 홍길동입니다. 나이는 30입니다.'
1
2
3
4
# f 문자열에서 정렬
f'{"hi":<10}'
f'{"hi":>10}'
f'{"hi":^10}'
'    hi    '
1
2
3
# f 문자열에서 공백채우기
f'{"hi":=^10}'
f'{"hi":!<10}'
'hi!!!!!!!!'
1
2
3
4
# f 문자열에서 소수점표현
y = 3.42134234
f'{y:0.4f}'
f'{y:10.4f}'
'    3.4213'
1
2
# f 문자열에서 { } 문자를 표시
f'{{ and }}'
'{ and }'

문자열 관련 함수들

  • 문자열 자료형은 자체적으로 함수를 가지고 있다.
  • 이들 함수를 다른 말로 문자열 내장 함수라 한다.
  • 이 내장 함수를 사용하려면 문자열 변수 이름 뒤에 ‘.’를 붙인 다음에 함수 이름을 써주면 된다.
1
2
3
# 문자 개수 세기 (count)
a = "hobby"
a.count('b')
2
1
2
3
4
# 위치 알려주기1 (find)
a = "Python is the best choice"
a.find('b')
a.find('k') # 찾는 문자가 없다면 -1을 반환.
-1
1
2
3
# 위치 알려주기2 (index)
a = "Life is too short"
a.index('t')
8

문자열 삽입(join)

1
",".join('abcd')
'a,b,c,d'
1
2
3
# 대문자를 소문자로 바꾸기
a = "HI"
a.lower()
'hi'
1
2
3
# 왼쪽 공백 지우기
a = " hi "
a.lstrip()
'hi  '
1
2
3
# 오른쪽 공백 지우기(rstrip)
a = " hi "
a.rstrip()
'  hi'
1
2
3
# 양쪽 공백 지우기(strip)
a = " hi "
a.strip()
'hi'

문자열 바꾸기(replace)

1
2
a = "Life is too short"
a.replace("Life", "your leg")
'your leg is too short'

문자열 나누기(split)

1
2
3
4
5
a = "Life is too short"
a.split()

b = "a:b:c:d"
b.split(':')
['a', 'b', 'c', 'd']
1
# 

2장 연습문제

  • 파이썬 프로그래밍의 기초, 자료형
1
2
3
4
5
6
7
8
9
# Q1 홍길동 씨의 과목별 점수는 다음과 같다. 홍길동 씨의 평균 점수를 구해 보자.
from IPython.core.display import Math

kor = 80
en = 75
math = 55

mean = (kor + en + math) / 3
print(mean)
70.0
1
2
3
4
5
6
7
# Q2 자연수 13이 홀수인지 짝수인지 판별할 수 있는 방법에 대해 말해 보자..
from IPython.core.display import Math

if 13 % 2 == 1 :
print("13은 홀수이다")
else :
print("13은 짝수이다")
13은 홀수이다
1
2
3
4
5
6
7
8
# Q3 자연수 13이 홀수인지 짝수인지 판별할 수 있는 방법에 대해 말해 보자..

num = "881120-1068234"
num1 = num[:6]
num2 = num[7:]

print(num1)
print(num2)
881120
1068234
1
2
3
4
#Q4 주민등록번호에서 성별을 나타내는 숫자를 출력해 보자.

pin = "881120-1068234"
print(pin[7])
1
1
2
3
4
5
6
#Q5 다음과 같은 문자열 a:b:c:d가 있다.
# 문자열의 replace 함수를 사용하여 a#b#c#d로 바꿔서 출력해 보자.

a = "a:b:c:d"
a.replace(":", "#")
print(a)
a:b:c:d
1
2
3
4
#Q6 [1, 3, 5, 4, 2] 리스트를 [5, 4, 3, 2, 1]로 만들어 보자.
a = [1,3,5,4,2]
a.sort(reverse=True)
print(a)
[5, 4, 3, 2, 1]
1
2
3
4
#Q7 ['Life', 'is', 'too', 'short'] 리스트를 Life is too short 문자열로 만들어 출력해 보자.

a = ['Life', 'is', 'too', 'short']
print(a[0] + " " + a[1] + " " + a[2] + " " + a[3])
Life is too short
1
2
3
4
5
#Q8 (1,2,3) 튜플에 값 4를 추가하여 (1,2,3,4)를 만들어 출력해 보자.

t1 = (1, 2, 3)
t2 = (4, )
t1 + t2
(1, 2, 3, 4)

Q9 다음과 같은 딕셔너리 a가 있다.

a = dict()
a
{}
다음 중 오류가 발생하는 경우를 고르고, 그 이유를 설명해 보자.
1.a[‘name’] = ‘python’
2.a[(‘a’,)] = ‘python’
3.a[[1]] = ‘python’
4.a[250] = ‘python’

1
2
3
4
5
6
7
8
9
#Q9 1번과 3번에서 오류가 발생합니다.
# 1번은 invalid syntax 오류
# 3번은 unhashable type: 'list' 오류
a = dict()
a
# a['name' = 'python']
a[('a',)] = 'python'
# a[[1]] = 'python'
a[250] = 'python'
1
2
3
4
5
#Q10 딕셔너리 a에서 'B'에 해당되는 값을 추출해 보자.
dict_00 = {'A':90, 'B':80, 'C':70}
d = dict_00.pop('B')
print(dict_00)
print(d)
{'A': 90, 'C': 70}
80
1
2
3
4
5
6
#Q11 a 리스트에서 중복 숫자를 제거해 보자.
# 다시 풀어보자
a = [1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5]
aset = set(a)
b = list(aset)
print(b)
[1, 2, 3, 4, 5]

Q12 파이썬은 다음처럼 동일한 값에 여러 개의 변수를 선언할 수 있다. 다음과 같이 a, b 변수를 선언한 후 a의 두 번째 요솟값을 변경하면 b 값은 어떻게 될까? 그리고 이런 결과가 오는 이유에 대해 설명해 보자.
a = b = [1, 2, 3]
a[1] = 4
print(b)

1
2
3
4
5
#Q12 
a = b = [1,2,3]
a[1] = 4
print(b)
# a=b 라고 설정했기 때문에 다음 결과가 나옵니다.
[1, 4, 3]

3장 연습문제

1
2
3
4
5
6
7
8
#Q1 다음 코드의 결괏값은?
a = "Life is too short, you need python"

if "wife" in a : print("wife")
elif "python" in a and "you" not in a : print("python")
elif "shirt" not in a : print("shirt")
elif "need" in a : print("need")
else: print("none")
shirt
1
2
3
4
5
6
7
8
9
#Q2 while문을 사용해 1부터 1000까지의 자연수 중 3의 배수의 합을 구해 보자.
count = 1
sum = 0
while count < 1000 :
count = count + 1
if count % 3 == 0 :
sum = sum + count

print(sum)
166833
1
2
3
4
5
#Q3 while문을 사용하여 다음과 같이 별(*)을 표시하는 프로그램을 작성해 보자.
count = 0
while count < 5:
count = count + 1
print("*" * count)
*
**
***
****
*****
1
2
3
#Q4 for문을 사용해 1부터 100까지의 숫자를 출력해 보자.
for num in range(100):
print(num+1)
1
2
3
4
5
6
7
8
9
10
#Q5 A 학급에 총 10명의 학생이 있다. 이 학생들의 중간고사 점수는 다음과 같다.
#[70, 60, 55, 75, 95, 90, 80, 80, 85, 100]
#for문을 사용하여 A 학급의 평균 점수를 구해 보자.
sum = 0
a_class = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100]
for num in a_class :
sum = sum + num

mean = sum / len(a_class)
print(mean)
79.0
1
2
3
4
5
6
7
8
9
10
11
12
13
#Q6 리스트 중에서 홀수에만 2를 곱하여 저장하는 다음 코드가 있다. 

numbers = [1, 2, 3, 4, 5]
result = []
for n in numbers:
if n % 2 == 1:
result.append(n*2)

# 위 코드를 리스트 내포(list comprehension)를 사용하여 표현해 보자.
# 다시 풀어보자
numbers = [1, 2, 3, 4, 5]
result = [n*2 for n in numbers if n%2==1]
print(result)
[2, 6, 10]