파이썬 입문
DB CAFE
thumb_up 추천메뉴 바로가기
- DBA { Oracle DBA 명령어 > DBA 초급 과정 > DBA 고급 과정 }
- 튜닝 { 오라클 튜닝 목록 }
- 모델링 { 데이터 모델링 가이드 }
목차
1 참고 url[편집]
파이썬 언어 기본 for Finance https://www.notion.so/for-Finance-355667aea8f34c169cd7c0f705aaa875 [PY4E] 모두를 위한 프로그래밍 : 파이썬 https://www.notion.so/PY4E-7573a4454709441fa035d5237163aff0
2 데이터 타입[편집]
# int
>>> a = 3
>>> type(a)
int
- float
- str
- bool
- complex
>>> c = 3 + 4j
>>> type(c)
complex
3 데이터 구조체[편집]
3.1 리스트[편집]
3.1.1 생성[편집]
>>> names = [ ]
>>> names = ['a', 'b', 'c', 'd, 'e']
3.1.2 len(s)[편집]
>>> names = ['a', 'b', 'c', 'd, 'e']
>>> len(names)
5
3.1.3 indexing[편집]
>>> names = ['a', 'b', 'c', 'd, 'e']
>>> names[0]
'a'
>>> names[1]
'b'
3.1.4 append[편집]
>>> names = ['a', 'b','c']
>>> names.append('d')
>>> names
['a', 'b', 'c', 'd']
3.1.5 insert[편집]
>>> names = ['a', 'b', 'c']
>>> names.insert(1, 'e')
>>> names
['a', 'e', 'b', 'c']
3.1.6 comprehension[편집]
- 컴프리핸션: 리스트를 한줄의 코드로 쉽게 만들때 사용
>>> data = [3, 4, 5]
>>> float_data = [float(d) for d in data]
3.2 튜플[편집]
3.2.1 생성[편집]
>>> names = ('a', 'b', 'c', 'd, 'e')
3.2.2 len(s)[편집]
>>> names = ('a', 'b', 'c', 'd, 'e')
>>> len(names)
5
3.2.3 indexing[편집]
>>> names = ('a', 'b', 'c', 'd, 'e')
>>> names[0]
'a'
>>> names[1]
'b'
3.3 딕셔너리[편집]
3.3.1 생성[편집]
>>> cur_price = { }
3.3.2 insert[편집]
>>> cur_price['samsung'] = 10000
>>> cur_price
{'samsung': 10000}
3.3.3 indexing[편집]
>>> cur_price['samsung']
>>> 10000
3.3.4 delete[편집]
>>> del cur_price['samsung']
>>> cur_price{}
3.3.5 key, value[편집]
>>> cur_price.keys()
dict_keys(['samsung'])
>>> cur_price.values()
dict_values([10000])
4 문자열 조작 함수[편집]
4.2 indexing[편집]
>>> mystring[0]
'h'
4.3 slicing[편집]
>>> mystring[0:5]
'hello'
>>> mystring[6:]
'world'
4.4 문자열.split(S)[편집]
>>> companies = "yahoo google"
>>> companies.split(' ')
['yahoo', 'google']
4.5 in[편집]
>>> 'google' in companies
True
4.6 combining[편집]
>>> s1 = "hello"
>>> s2 = "world"
>>> s3 = s1 + ' ' + s2
>>> s3
"hello world"
4.7 replace[편집]
>>> a = "yahoo;google"
>>> new_a = a.replace(';', '-')
>>> new_a
"yahoo-google"
4.8 index[편집]
>>> s = "yahoo google"
>>> s.index("google")
6
4.9 문자열.find(x)[편집]
>>> s = "yahoo google"
>>> s.find("google")
6
4.10 stripping[편집]
>>> a = " yahoo "
>>> new_a = a.strip()
>>> new_a
"yahoo"
4.11 데이터 형변환[편집]
다음과 같이 데이터를 다른 자료형으로 Casting 할 수 있다.
>>> float(3) #실수형으로 바꿈
3.0
>>> int(3.0) #정수형으로 바꿈
3
>>> int('0xc', 16)
>>> int('0o14', 8)
두 번째 인자에 입력 값의 진수를 명시하면 된다. 다른 벡터 형으로 변환할 수도 있다.
>>> str(3) #문자열로 바꿈
'3'
>>> hex(12) #16진수로 바꿈
'0xa'
>>> oct(10) #8진수로 바꿈
'0o12'
>>> bin(10) #2진수로 바꿈
'0b1010'
다시 10진수로 바꿀 때는 자동으로 바뀐다.
>>> tuple([1,2]) #리스트를 튜플로 바꿈
(1, 2)
>>> list((1,2)) #튜플을 리스트로 바꿈
[1, 2]
>>> set([1,2]) #리스트를 집합 데이터형으로 바꿈
{1, 2}
5 딕셔너리로 캐스팅[편집]
딕셔너리로 캐스팅 하는 것은 조금 까다로운데 key 값을 어떻게 설정할 것인가를 정해야 하기 때문. key와 value가 한 쌍으로 된 경우 딕셔너리로 캐스팅 할 수 있다.
>>> dict([[1,2],[3,4]])#쌍으로 된 경우만 딕셔너리형으로 변환된다.
{1: 2, 3: 4}
5.1 유니코드로 변환[편집]
>>> ord(‘가’) #문자를 유니코드 값으로 변환
44032 #44032는 ‘가’의 유니코드 값
>>> chr(44032). #chr()함수는 유니코드 값을 문자로 변환한다.
‘가’
6 파이썬 제어문[편집]
6.1 조건별 분기[편집]
if ending_price > 10000:
print("sell")
elif ending_price < 8000:
print("buy")
else:
print("hold")
6.2 반복 처리[편집]
- Loop – For
>>> for i in range(0, 5):
print(i)
0
1
2
3
4
>>> for i in range(0, 5):
if i % 2 == 0:
print(i, end=' ')
0, 2, 4
>>> buy_list = ['000660', '039490']
>>> for code in buy_list:
print("buy", code)
buy 000660
buy 039490
>>> hold_list = {'naver': 10, 'samsung': 20}
>>> for company, num in hold_list.items():
print(company, num)
naver 10
samsung 20
6.3 Loop - While[편집]
>>> i = 0
>>> while i < 5:
print(i)
i += 1
0
1
2
3
4
>>> i = 0
>>> while i < 5:
if i % 2 == 0:
print(i)
i += 1
0 2 4
7 파이썬 모듈 임포트 방법[편집]
- 일반적인 import 방식
import os
- 필요 함수만 import 하는 방식
from os import xxx
- 모든 함수를 import 하는 방식
from os import *
9 함수[편집]
>>> def cal_upper_price(price):
increment = price * 0.3
upper_price = price + increment
return upper_price
>>> upper_price = cal_upper_price(10000)
>>> upper_price
13000
10 모듈[편집]
# stock.py
def cal_upper_price(price):
increment = price * 0.3
upper_price = price + increment
return upper_price
- stock.py 모듈 import
# test.py
import stock
upper_price = stock.cal_upper_price(10000)
- stock.py 모듈 import
# test.py
from stock import *
upper_price = upper_price(10000)
11 클래스[편집]
- 클래스 정의(Class Definitions)
- Class: 인스턴스의 청사진 , a blueprint for an instance ("instance factories")
- Instance: 클래스의 생성된 객체 , a constructed object of the class
- Type: 인스턴스가 속한 (타입별)클래스를 가르킴 , indicates the class the instances belong to
- Attribute: 모든 객체 값 ,any object value: object.attribute
- Method: 클래스에 선언된 호출 가능한 속성 , a "callable attribute" defined in the class
11.1 인스턴스 메소드[편집]
class Joe:
def callme(self):
print("calling 'callme' method with instance")
thisjoe = Joe() #인스턴스 할당
thisjoe.callme() #메소스 호출
11.2 클래스 정의[편집]
class BusinessCard:
def __init__(self, name, email):
self.name = name
self.email = email
def print_info(self):
print(self.name)
print(self.email)
# instantiation and call the method
mem1 = BusinessCard("Goo", "goo@gmail.com")
mem1.print_info()
11.3 클래스 상속[편집]
- Class – Inheritance
>>> class Parent:
def can_sing(self):
print("sing a song")
>>> father = Parent()
>>> father.can_sing()
sing a song
>>> class LuckyChild(Parent):
pass
>>> child1 = LuckyChild()
>>> child1.can_sing()
sing a song
>>> class LuckyChild2(Parent):
def can_dance(self):
print("dance beautifully")
>>> child2 = LuckyChild2()
>>> child2.can_sing()
sing a song
>>> child2.can_dance()
dance beautifully
11.4 클래스 상속2[편집]
- Class – Inheritance II
>>> class Parent:
def __init__(self):
self.money = 10000
>>> class Child1(Parent):
def __init__(self):
super().__init__()
>>> class Child2(Parent):
def __init__(self):
pass
>>> child1 = Child1() #Parent의 __init__ 를 할당 받은경우
>>> child2 = Child2() #받지 않은 경우
>>> print(child1.money)
10000
>>> print(child2.money)
AttributeError: 'Child2' object has no attribute 'money'