메뉴 여닫기
개인 메뉴 토글
로그인하지 않음
만약 지금 편집한다면 당신의 IP 주소가 공개될 수 있습니다.

파이썬 초보자 입문서: 두 판 사이의 차이

데브카페
새 문서: == 파이썬 기본기 다지기 == == 참고 url == 파이썬 언어 기본 for Finance https://www.notion.so/for-Finance-355667aea8f34c169cd7c0f705aaa875 [PY4E] 모두를 위한 프로그래밍 : 파이썬 https://www.notion.so/PY4E-7573a4454709441fa035d5237163aff0 == 데이터 타입 확인 == <source lang=python> # int >>> a = 3 >>> type(a) int </source > # float # str # bool # complex <source lang=python> >>> c = 3 + 4j >>> type(c) complex </source> == 데이터 구...
 
잔글 Devcafe님이 파이썬 입문 문서를 파이썬 초보자 입문서 문서로 이동했습니다
 
(같은 사용자의 중간 판 2개는 보이지 않습니다)
1번째 줄: 1번째 줄:
== 파이썬 기본기 다지기 ==
# 기초 문법
== 참고 url ==
# [[PYTHON 데이터형]]|데이터 형
파이썬 언어 기본 for Finance https://www.notion.so/for-Finance-355667aea8f34c169cd7c0f705aaa875
# [[Python class]]|클래스
# [[Py qt]]|GUI 프로그램 만들기
# 데이터베이스 연결
# 파이썬 확장 모듈
# 파이썬 라이브러리 활용법


[PY4E] 모두를 위한 프로그래밍 : 파이썬 https://www.notion.so/PY4E-7573a4454709441fa035d5237163aff0
[[category:주식]]
 
[[category:python]]
== 데이터 타입 확인 ==
<source lang=python>
# int
>>> a = 3
>>> type(a)
int
</source >
 
# float
# str
# bool
# complex
 
<source lang=python>
>>> c = 3 + 4j
>>> type(c)
complex
</source>
 
== 데이터 구조체 ==
=== 리스트 (LIST) ===
{{틀:고지상자
|제목= 리스트 타입 표현식
|내용= [ ] 으로 표현
}}
# 파이썬에는 배열은 없으며 대신에 index를 부여할 수 있는 시퀀스 타입을 제공.
# 파이썬에서 시퀀스 타입의 특징은 저장하고 있는 데이터가 순서를 가진다는 점이며, 그 중 하나가 list 타입.
# 배열과 거의 흡사하다고 볼수 있다.
# list에 담을 수 있는 타입에는 제한이 없음
## 정수, 문자열 등의 타입뿐만 아니라 모든 타입의 객체 및 다른 list 객체
##:<source lang=python> my_list = [1, 'hello', 3.7, [7, 8, 9], {"a": 2, "b": 3}]</source>
 
==== 생성 ====
<source lang=python>
>>> names = [ ]
>>> names = ['a', 'b', 'c', 'd’, 'e']
</source>
또는
<source lang=python>
>>> names  = list()
>>> names.append('a')
>>> names.append('b')
 
</source>
 
==== 인덱싱 (indexing) ====
<source lang=python>
>>> names = ['a', 'b', 'c', 'd’, 'e']
>>> names[0]
'a'
>>> names[1]
'b'
</source>
 
==== append (리스트 뒤에 추가) ====
<source lang=python>
>>> names = ['a', 'b','c']
>>> names.append('d')
>>> names
['a', 'b', 'c', 'd']
 
>>> my_list = [1, 3, 5]
>>> my_list.append(100)
>>> my_list
[1, 3, 5, 100]
>>> my_list.append([200, 300])
>>> my_list
[1, 3, 5, 100, [200, 300]]
</source>
 
==== insert (특정위치에 추가) ====
<source lang=python>
>>> names = ['a', 'b', 'c']
>>> names.insert(1, 'e')
>>> names
['a', 'e', 'b', 'c']
</source>
==== 확장 (extend) ====
# list 객체에 새로운 list를 더하여 확장.
# extend(x) 에서 x에는 iterable을 구현한 객체만 사용 가능한데, 시퀀스 타입의 자료형들은 모두 iterable을 구현했으므로 사용 가능.
# append(x) 와의 차이점은 append()는 하나의 요소로서 추가되지만 extend()는 확장 개념으로 추가된다는 점.
* 똑같은 list를 추가해보면 바로 차이점을 알 수 있음.
<source lang=python>
>>> my_list = [1, 3, 5]
>>> my_list.extend([100, 200, 300])
>>> my_list
[1, 3, 5, 100, 200, 300]
</source>
 
==== 요소 제거 (remove) ====
<source lang=python>
>>> my_list = [1, 3, 1, 3]
>>> my_list.remove(1)
>>> my_list
[3, 1, 3]
>>> my_list.remove(3)
>>> my_list
[1, 3]
</source>                             
또는 DEL 키워드 사용
<source lang=python>
>>> my_list = [1, 3, 1, 3]
>>> del my_list[1]
>>> my_list
[1, 1, 3]
</source>                             
 
==== list 값 꺼내기 (pop) ====
# list의 요소 중 끝의 요소를 꺼내어 반환.
# 복사가 아닌 꺼내는 것이기 때문에 꺼낸 요소는 list 객체에서 사라짐.
 
<source lang=python>
>>> my_list = [1, 3, 1, 3]
>>> my_list.pop()
3
>>> my_list
[1, 3, 1]
</source>                             
 
* pop(index) 로 사용하면 index 위치의 요소 값을 꺼냅니다.
<source lang=python>
>>> my_list = [1, 3, 1, 3]
>>> my_list.pop(1)
3
>>> my_list
[1, 1, 3]
</source>
 
==== list 정렬 (sort) ====
 
list의 요소 값들을 오름차순으로 정렬.
 
<source lang=python>
>>> my_list = [1, 3, 1, 3]
>>> my_list.sort()
>>> my_list
[1, 1, 3, 3]
</source>                                                                                                                         
 
내림차순으로 정렬하는 경우는 reverse 값을 True.
 
<source lang=python>
>>> my_list = [1, 3, 1, 3]
>>> my_list.sort(reverse=True)
>>> my_list
[3, 3, 1, 1]
</source>                             
 
==== list 거꾸로 뒤집기 (reverse) ====
list의 요소를 거꾸로.
<source lang=python>
>>> my_list = [1, 2, 3, 4]
>>> my_list.reverse()
>>> my_list
[4, 3, 2, 1]
</source>                             
==== len(s) ====
<source lang=python>
>>> names = ['a', 'b', 'c', 'd, 'e']
>>> len(names)
5
</source>
==== COUNT list 특정 값 개수 카운트====
<source lang=python>
>>> my_list = [1, 2, 3, 4, 1, 2, 3, 4]
>>> my_list.count(1)
2
</source>
 
==== comprehension ====
* 컴프리핸션: 리스트를 한줄의 코드로 쉽게 만들때 사용 
<source lang=python>
>>> data = [3, 4, 5]
>>> float_data = [float(d) for d in data]
</source>
 
==== 문자열을 리스트로 형변환 ====
<source lang=python>
>>> my_str = 'python'
>>> my_list = list(my_str)
>>> my_list
['p', 'y', 't', 'h', 'o', 'n']
</source>
 
==== 다차원 리스트  ====
# 파이썬에서는 모든 것들이 객체이기 때문에 변수에 무엇을 집어넣든지 실제 그 객체가 들어가는 것이 아닌 객체를 가리키는 객체의 참조 주소값이 변수에 할당됩니다.
# list의 요소들도 사실은 실제 값이 아닌 요소에 할당된 객체의 주소를 가리키고 있습니다.
# 다차원 list를 만들게 되면 또 다른 list가 생성되고 그 list의 주소값을 요소로 가지고 있는 것입니다.
 
* 실제로는 나머지 요소들도 실제 정수 값이 아닌 정수 객체를 가리키는 주소값이 들어가 있습니다.
 
<source lang=python>
>>> my_list = [1, 3, 5, [11, 13, 15]]
>>> my_list
[1, 3, 5, [11, 13, 15]]
>>> my_list[3]
[11, 13, 15]
</source>
 
==== 리스트 요소에 index 범위로 접근 ====
# 파이썬에서 list같은 시퀀스 타입 자료구조의 장점은 다양한 방법으로 요소들을 접근할 수 있다는 점.
# 데이터를 다루는데, 매우 유연하게 코드를 작성할 수 있으며, 머릿속에 생각한대로 직관적으로 데이터를 다룰 수 있음.
 
<source lang=python>
>>> my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> my_list[9:]  # [9]부터 이후의 모든 요소
[10, 11, 12]
>>> my_list[:4]  # [4] 이전의 모든 요소
[1, 2, 3, 4]
>>> my_list[::3]  # 요소를 3씩 건너 뛰며 접근
[1, 4, 7, 10]
>>> my_list[1:5]  # [1] 부터 [5] 이전까지
[2, 3, 4, 5]
>>> my_list[3::2]  # [3] 부터 2씩 건너 뛰며 접근
[4, 6, 8, 10, 12]
</source>
 
==== list객체 + 연산 ====
<source lang=python>
>>> my_list = [1, 3, 5, 7, 9]
>>> my_list = my_list + my_list
>>> my_list
[1, 3, 5, 7, 9, 1, 3, 5, 7, 9]
</source>
==== list객체 * 연산 ====
<source lang=python>
>>> my_list = [1, 3, 5, 7, 9]
>>> my_list * 3
[1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9]
</source>
==== list 요소 값 부분 수정 ====
<source lang=python>
>>> my_list = [1, 3, 5, 7, 9]
>>> my_list[3] = 10
>>> my_list
[1, 3, 5, 10, 9]
</source>
 
==== list 요소 인덱스 범위 연산으로 수정 ====
# 리스트[시작:끝] 범위연산을 같이 사용하면 한꺼번에 값을 수정할 수 있음.
# 주의할점은 my_list[3] = [1,2] 와 같은 식으로 수정하려 하면 범위 수정이 아닌 [3] 요소에 [1,2] list가 들어가서 [1, 3, 5, [1, 2], 9] 과 같이 2차원 list가 되어버린다는 점.
# [0:3]은 [0], [1], [2] 를 의미하므로 해당 범위를 수정하기 위해 삭제
 
=== 튜플 ===
{{틀:고지상자
|제목= 튜플 타입 표현식
|내용= ( ) 으로 표현
}}
==== 생성 ====
<source lang=python>
>>> names = ('a', 'b', 'c', 'd, 'e')
</source>
 
==== len(s) ====
<source lang=python>
>>> names = ('a', 'b', 'c', 'd, 'e')
>>> len(names)
5
</source>
==== indexing ====
<source lang=python>
>>> names = ('a', 'b', 'c', 'd, 'e')
>>> names[0]
'a'
>>> names[1]
'b'
</source>
 
=== 딕셔너리 ===
{{틀:고지상자
|제목= 딕셔너리 타입 표현식
|내용= { } 으로 표현
}}
==== 생성 ====
<source lang=python>
>>> cur_price = { }
</source>
 
==== insert ====
<source lang=python>
>>> cur_price['samsung'] = 10000
>>> cur_price
{'samsung': 10000}
</source>
==== indexing ====
<source lang=python>
>>> cur_price['samsung']
>>> 10000
</source>
 
==== delete ====
<source lang=python>
>>> del cur_price['samsung']
>>> cur_price{}
</source>
 
==== key, value ====
<source lang=python>
>>> cur_price.keys()
dict_keys(['samsung'])
>>> cur_price.values()
dict_values([10000])
</source>
 
== 기본 함수 ==
=== print ===
=== 다중 변수 print ===
<source lang=python>
print("City", city, 'is in the country', country)
</source>
==== 값을 매개 변수로 전달 ====
<source lang=python>
print("City {} is in the country {}".format(city, country))
</source>
==== 문자열 형식 사용 ====
순차적 옵션
<source lang=python>
print("City {} is in the country {}".format(city, country))
</source>
숫자 서식
<source lang=python>
print("City {1} is in the country {0}, yes, in {0}".format(country, city))
</source>
명시 적 이름으로 형식화
<source lang=python>
print("City {city} is in the country {country}".format(country=country, city=city))
</source>
==== 튜플로 인수를 전달 ====
<source lang=python>
print("City %s is in the country %s" %(city, country))
</source>
==== Only from Python 3.6 ====
<source lang=python>
print(f"City {city} is in the country {country}".format(country=country, city=city))
</source>
 
== 문자열 조작 함수 ==
 
=== len(s) ===
<source lang=python>
>>> mystring = "hello world"
>>> len(mystring)
11
</source>
[[파일:Python-slicing.jpg|섬네일|600px]]
=== indexing ===
<source lang=python>
>>> mystring[0]
'h'
</source>
 
=== slicing ===
<source lang=python>
>>> mystring[0:5]
'hello'
 
>>> mystring[6:]
'world'
</source>
 
=== 문자열.split(S) ===
<source lang=python>
>>> companies = "yahoo google"
 
>>> companies.split(' ')
['yahoo', 'google']
</source>
 
=== in ===
<source lang=python>
>>> 'google' in companies
True
</source>
 
=== combining ===
<source lang=python>
>>> s1 = "hello"
>>> s2 = "world"
>>> s3 = s1 + ' ' + s2
>>> s3
"hello world"
</source>
 
=== replace ===
<source lang=python>
>>> a = "yahoo;google"
>>> new_a = a.replace(';', '-')
>>> new_a
"yahoo-google"
</source>
 
=== index ===
<source lang=python>
>>> s = "yahoo google"
>>> s.index("google")
6
</source>
 
=== 문자열.find(x) ===
<source lang=python>
>>> s = "yahoo google"
 
>>> s.find("google")
6
</source>
 
=== stripping ===
<source lang=python>
>>> a = "  yahoo  "
>>> new_a = a.strip()
>>> new_a
"yahoo"
</source>
 
=== 데이터 형변환 ===
 
다음과 같이 데이터를 다른 자료형으로 Casting 할 수 있다.
<source lang=python>
>>> 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}
</source>
 
== 딕셔너리로 캐스팅 ==
# 딕셔너리로 캐스팅 하는 것은 조금 까다로운데 key 값을 어떻게 설정할 것인가를 정해야 하기 때문.
# key와 value가 한 쌍으로 된 경우 딕셔너리로 캐스팅 할 수 있다.
<source lang=python>
>>> dict([[1,2],[3,4]])#쌍으로 된 경우만 딕셔너리형으로 변환된다.
{1: 2, 3: 4}
</source>
==== 유니코드로 변환 ====
<source lang=python>
>>> ord(‘가’)    #문자를 유니코드 값으로 변환
44032  #44032는 ‘가’의 유니코드 값
>>> chr(44032). #chr()함수는 유니코드 값을 문자로 변환한다.
‘가’
</source>
 
== 파이썬 제어문 ==
=== 조건별 분기 ===
<source lang=python>
if ending_price > 10000:
    print("sell")
elif ending_price < 8000:
    print("buy")
else:
    print("hold")
</source>
=== 반복 처리  ===
* Loop – For
<source lang=python>
>>> for i in range(0, 5):
        print(i)
 
0
1
2
3
4
</source>
<source lang=python>
>>> 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
</source>
 
=== Loop - While ===
<source lang=python>
>>> 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
</source>
 
== 파이썬 모듈 임포트 방법 ==
* 일반적인 import  방식 
<source lang=python>
import os
</source>
 
* 필요 함수만 import 하는 방식
<source lang=python>
from os import xxx
</source>
 
* 모든 함수를 import 하는 방식
<source lang=python>
from os import *
</source>
 
== 변수 ==
[[파일:Python-var.jpg|섬네일|700px]]
<source lang=python>
>>> a = 10
>>> id(a)
</source >
 
== 함수 선언 ==
<source lang=python>
>>> 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
</source >
 
== 모듈 ==
<source lang=python>
# stock.py
def cal_upper_price(price):
    increment = price * 0.3
    upper_price = price + increment
    return upper_price
</source>
 
* stock.py 모듈 import
<source lang=python>
# test.py
import stock
upper_price = stock.cal_upper_price(10000)
</source>
 
* stock.py 모듈 import
<source lang=python>
# test.py
from stock import *
upper_price = upper_price(10000)
</source>
 
== 클래스 ==
* 클래스 정의(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
 
=== 인스턴스 메소드 ===
<source lang=python>
class Joe:
    def callme(self):
        print("calling 'callme' method with instance")
 
thisjoe = Joe() #인스턴스 할당
thisjoe.callme() #메소스 호출
</source>
 
=== 클래스 정의 ===
<source lang=python>
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()
</source>
 
=== 클래스 상속 ===
* Class – Inheritance
<source lang=python>
>>> 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
</source>
 
=== 클래스 상속2 ===
* Class – Inheritance II
 
<source lang=python>
>>> 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'
</source>
 
[[Category:python]]

2025년 6월 11일 (수) 00:59 기준 최신판

  1. 기초 문법
  2. PYTHON 데이터형|데이터 형
  3. Python class|클래스
  4. Py qt|GUI 프로그램 만들기
  5. 데이터베이스 연결
  6. 파이썬 확장 모듈
  7. 파이썬 라이브러리 활용법

Comments