머신 러닝

[데이터과학 코세라 강의] (3주차-2) 데이터 과학을 위한 파이썬

마빈 Marvin 2022. 5. 21. 01:46

3주차에서는 다음 5가지 주제를 하는데, 이번 포스팅에서는 나머지 2가지에 대해서 적어보겠다.

   - Conditions and Branching

  - Loops

  - Functions

  - Exception Handling

  - Objects and Classes

 

구글 colab ipython 링크에 3주차 내용을 수록해두었다.

 

 

Exception Handling

예: 문자만 넣어야 하는데 숫자를 넣는 경우, 파일을 열고자 하는데 실패하는 경우.

try: ... except IOError: ... else: ... 

ZeroDivisionError, NameError, IndexError

Exception Handling

x=2
try:
  y=int(input("number you want to divide by x"))
  x = x/y
  print("success x = ",x)
except:
  print("Error exists")

위와 같이 코드를 만들면, 아래와 같이 number you want to divide by x 옆에 빈칸이 나온다. 

빈칸에 0 이나 정수 이외의 숫자(예:0.5) 를 넣고 엔터를 치면 "Error exists" 가 출력된다. 정수를 넣으면 success 와 함께 x = 새로운값이 출력된다. 

이러한 exception 을 하는 이유는 에러를 파악하기 위해서다. 

 

Object and Classes

object 는 type 들이 있다. 

type(1) 은 int 

type(1.5) 은 float

type([1,2]) 은 list

type("The sea is blue") 은 str

type({"suceed":1, "fail":0}) 은 list

Methods

예: sorting

rank = [10,4,3,5,6,1,2,8,7,9]

rank = [10,4,3,5,6,1,2,8,7,9]
rank

 [10,4,3,5,6,1,2,8,7,9] 를 출력한다.

rank.sort()
rank

 는 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 를 출력한다.

rank.reverse()
rank

는 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 를 출력한다. 

Class

class 는 데이터 attribute 와 method 가 있다.

attribute

class nameClass(objectClass):

class product:
  def __init__(self,price,weight,topic):
    self.price=price
    self.weight=weight
    self.topic=topic

cabbage=product(2.04,74,'vegetable')
cabbage.price

는 2.04 를 출력한다.

숫자를 변화시킬 수 있다. 예를 들어, 양배추 가격이 2.04$ 에서 3$ 로 상승했다고 해보자. 

cabbage.price=3
cabbage.price

는 변화된 3을 출력시킨다. 

Methods

method 는 data attribute 를 변화시킨다.

class product:
  def __init__(self,price,weight,topic):
    self.price=price
    self.weight=weight
    self.topic=topic
  def cpi_adj(self,cpi):
    self.price=self.price*cpi
    return(self.price)  

cabbage=product(2.04,74,'vegetable')

로 변경후 

cabbage.cpi_adj(1.05)

는 2.142 에 가까운 값을 출력한다. 

 

 

추가로 영상에서는 직접 그림을 그리는 코드를 drawCircle 이나 drawRectangle 로 정의하기도 한다.