머신 러닝

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

마빈 Marvin 2022. 5. 20. 07:39

 

 

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

   - Conditions and Branching

  - Loops

  - Functions

  - Exception Handling

  - Objects and Classes

 

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

 

 

Conditions and Branching

Conditions

x=6, y=7 을 정한 후 x==y 를 입력하면 False 가 출력된다. x < y 를 입력하면 True 가 출력된다. x!=y 를 입력하면 True 가 출력된다. "Ed Sheeren"=="Justin Bieber" 는 False 를 출력하고 "Ed Sheeren" != "Justin Bieber"는 True 를 출력한다. 

Branching

internationalAge = 18

if (internationalAge>=19):

   print("you can drink in Korea")
else:
  print("you cannot drink in Korea")

 

internationAge 가 20이면, "you can drink in Korea" 를 출력하고,  internationalAge 가 18이면, "you cannot drink in Korea" 를 출력한다. 

elif 문은 else if 문의 줄임표현이다. 

internationalAge = 18
if (internationalAge>=19):
  print("you can drink and get driver license in Korea")
elif(internationalAge==18):
  print("you cannot drink but get driver's license in Korea")
else:
  print("you can neither drink nor get driver's license in Korea")

위 표현은 만 19 세 이상이면 음주와 운전면허 취득 가능, 만 18세이면 운전면허 취득은 가능하나 음주는 불가능하고, 만 18세 미만이면 운전면허와 음주 둘 다 불가능이라는 표현이다. 

LogicOperators

not(True) 는 False, not(False) 는 True

A or B 에서 A 와 B 가 모두 False 일 때만 False 를 출력한다. 

장을 함께 보러가는데, 내가 좋아하는 두 개의 아이템 중에 적어도 하나가 장바구니에 있는지 확인하고 싶다고 하자. 

item1 = "apple juice"
item2 = "orange juice"
groceryList = {"carrot", "milk", "cabbage", "orange juice", "apple juice", "meat"}
if (item1 in groceryList) or (item2 in groceryList):
  print("My favorite juice is included in the grocery list")
else:
  print("My favorite juice is not included in the grocery list")

위와 같이 코드를 짜면, "My favorite juice is included in the grocery list" 가 출력된다. 

A and B 에서 A 와 B 가 모두 True 일때만 True 를 출력한다. 

장을 함께 보러가는데, 내가 좋아하는 두 개의 아이템이 모두 장바구니에 있는지 확인하고 싶다고 하자. 

item1 = "apple juice"
item2 = "orange juice"
groceryList = {"carrot", "milk", "cabbage", "orange juice", "apple juice", "meat"}
if (item1 in groceryList) and (item2 in groceryList):
  print("All of my two most favorite juices are included in the grocery list")
else:
  print("Not all of my two most favorite juice are not included in the grocery list")

위와 같이 코드를 짜면, 나의 최애 쥬스 두 개가 모두 장바구니에 출력되어있다는 문구가 출력된다. 

 

 

Loops

for loop

n = 5
for i in range(n):
  print(i)

을 해보면, 0,1,2,3,4 가 출력된다. 

x=range(2,7)
for i in x:
  print(i)

을 해보면, 2,3,4,5,6 이 출력된다. 

for loop 을 이용해서 i 번째 인덱스의 값을 수정할 수 있다. 

colors = ["red","orange","yellow","green","blue","indigo","purple"]
for i in range(0,4):
  colors[i]="white"
colors

는 ['white', 'white', 'white', 'white', 'blue', 'indigo', 'purple'] 를 출력한다. 

rainbow = ["red","orange","yellow","green","blue","indigo","purple"]
for color in rainbow:
  print(color)

를 출력하면, red, orange, yellow, green, blue, indigo, purple 이 차례대로 출력된다. 

for i,color in enumerate(rainbow):
  print(i, color)

는 출려값으로

0 red 1 orange 2 yellow 3 green 4 blue 5 indigo 6 purple 를 출력한다. 

while loop

조건이 충족하는 동안에만 loop 이 진행된다. 

successRec = ["yes","yes","no","yes","yes","no","yes"]
newSucRec = []
i=0
while(successRec[i]=="yes"):
  newSucRec.append(successRec[i])
  i=i+1
newSucRec

는 ['yes', 'yes'] 를 출력한다. 

 

Functions

유저가 직접 function 을 만들 수 있다. input 에 값을 넣으면, output 이 출력된다. 

def fuc1(x):
  y = x + 1;
  return y
fuc1(5)

는 (5+1=)6을 출력한다. 

파이썬에는 내장된 함수가 있다. 

Len

len 은 list 나 dictionary 의 길이를 출력한다. 

scores=[5,4,3,4,4,2]
len(scores)

는 6을 출력한다. 

sum

sum 은 list 나 tuple 내부의 값의 합을 출력한다. 

sum(scores)

는 22를 출력한다. 

sorted vs sort

sorted 는 기존 list 의 값을 변화시키지 않는다. 

sorted_scores = sorted(scores)
sorted_scores

에서 sorted_scores 를 출력하면 [2, 3, 4, 4, 4, 5] 가 출력되지만, 기존의 scores 를 출력하면 [5, 4, 3, 4, 4, 2] 값이 나온다. 

반면에, sort 를 사용하면, 기존 값이 sort 가 된다. 

scores.sort()
scores

를 하면, [2, 3, 4, 4, 4, 5] 가 출력된다. 

파이썬 함수 만들기

형식은 def ... return 이다. 

def mul2(x):
  """
  multiply by 2
  """
  y = 2*x
  return y
a = mul2(25)
a

 

는 50을 출력한다. 

그리고 """ ... """ 은 해당 함수에 대한 도큐멘트인데, help(함수명)을 하면 출력된다. 

help(mul2)

를 하면, Help on function mul2 in module __main__: mul2(x) multiply by 2 가 출력된다. 

한편, x 값에 숫자가 아닌 string 을 넣으면, string 값이 두 번 출력된다. 

mul2("work! ")

는 work! work! 를 출력한다. 

함수는 여러 개의 parameter 를 가질 수 있다. 

import math
def dist(x,y):
  l=math.sqrt(x**2+y**2)
  return l
dist(3,4)

는 5를 출력한다. (note: x**2 는 x의 제곱이고, math.sqrt(a) 함수는 a의 루트값을 출력한다)

def greet():
  print("Hello!")
greet()

함수에 parameter 를 따로 적용하지 않고, 위와 같이 했을 때, greet() 에 대한 출력값은 Hello! 이다. 챗봇 만들거나 할 때 도움이 되는 개념이 아닐까 생각이 든다. 

def nothing():
  pass
print(nothing())

는 none 를 출력한다. 

def whatDist(x,y):
  l = math.sqrt(x**2+y**2)
  print("distance between ",x," and ",y," is ",l)
whatDist(3,4)

는 distance between  3  and  4  is  5.0 를 출력한다. 

writing = [0.75, 0.45, 0.55, 0.90]
def printSucRate(habit):
  for i,j in enumerate(habit):
    print("Day",i,"score is",j)

printSucRate(writing)

를 출력하면, Day 0 score is 0.75 Day 1 score is 0.45 Day 2 score is 0.55 Day 3 score is 0.9 이 출력된다. 

 

 

Collecting arguments

authors = ["twain", "hemingway", "Orwell"]
def authorNames(*lastName):
  for name in lastName:
    print(name)

authorNames(authors)

는 ['twain', 'hemingway', 'Orwell'] 를 출력한다. 

newAuthors = ["King","Rowling","haruki"]
authorNames(newAuthors)

는 ['King', 'Rowling', 'haruki'] 를 출력한다. 

Scope: 함수 안에서 정의되는 변수의 경우는 함수 바깥에서 정의되지 않는다.

만약, variable 이 함수 안에 없으면, 바깥에서 동일한 변수가 있는지 찾고 이를 함수의 변수명으로 지정한다. 

함수 안에 global varName 으로 지정하면, 함수 바깥에서도 varName 을 사용 가능하다.