반응형
python 3.7.2를 사용해서 책에서 나오는 문제를 사용해 본다.
Why Python??
- C를 주로(한... 10년 정도? ) 사용해본 입장에서 C로만 개발을 진행하기에는 많은 에로 사항이 존재한다.
- 불편한점은...
- 문자열의 수정이 어렵다.
- 예를 들어서 C언에서 "hello"라는 문자열을 만들어 본다면...
- 1) char[] array = {'h', 'e', 'l','l','o'};
- 2) printf("%s", array);
- 두 줄로 "생성"이 가능하다, 그리고 "hello"라는 문자 뒤에 느낌표를 붙여 주려면...
- 3) cha array2[r[strlen(array)+1];
- 4) array의 5문자를 array2로copy해주고 마지막 !를 추가해준다.
- 복잡한 과정을 수행해아한다.
C를 이용해서 문자열을 수정할 경우 한 글자를 추가하는 경우에도 전체 array를 새로 생성해서 copy하는 과정을 명시적으로 수행해야한다. - 메모리가 낭비 되기 쉽다(편하게 사용하려면)
물론 이런 과정을 수행하지 않고 사용할 수는 있겠지만, 사용하지 않는 영역까지 미리 선언해 둔 상태에서 실행해야하기 때문에 메모리의 낭비가 있다.
(ex - 5글자를 저장하는 경우에도 후에 몇 글자가 추가로 붙을 지 알 수 없기 때문에 20글자 만큼의 '저장소'를 미리 생성해 두어야 한다. ) - Python(java, java script) 같은 스크립트 언어를 사용할 경우에는 자유 자재로 추가하고, 제거할 수 있다.
1. 모듈 추가 사용하기
- import를 하기 위한 방법은 다양하게 적용이 가능하다.
- 다양한 경로에 있는 기능을 추가하거나,
- 특정 파일의 일부 Function/Class만 import 해서 사양할 수 있다.
- 방식의 선택은 자유가 되겠지만, 각 방식별로 특징을 알아 두어야 후에 큰 사이즈의 프로그램을 작성할 때 유용하게 사용이 가능하다.
1.1 같은 폴더에서 import
/test/test1.py에서 /test/test.py를 import 하는 경우
import test
1.2 다른 폴더에 존재하는 파이선 파일 import
/test/test1.py 에서 /data/python/test.py를 import 하는 경우
import sys <-- sys module을 import
sys.path.insert(0, "/data/python/test.py") <-- system path로 추가
import test <-- 다른 폴더에 있는 test 를 import 성공
다른 경로에 있는 파일의 import하기 위해서는 해당 경로를 system path에 추가해 주어야 한다.
1.3 하위 폴더를 import
import 할 하위 폴더에 __init__.py(내용 없어도 상관 없음)을 추가해 준다. 예를 들어서
test/test1.py에서 test/lib/a.py를 import할 경우, test/lib/__init__.py를 추가해준다.
//test1.py
import lib.a
1.4 특정 Class or Fucntion만 import하기 (출처:[Python 파이썬] from 과 import 사용법 )
여기서는 파일내부의 특정 코드만을 import 하는 방법 2가지를 한꺼번에 설명한다.
/home/a.py 에서 /home/b.py 의 Human Class를 import 하는 경우
/home/a.py 에서 /home/c.py 의 getName Function을 import 하는 경우
/home/a.py 에서 /home/lib/d.py 의 getHometown Function을 import 하는 경우
============== b.py ==============
class Human:
def __init__(self, name):
self.name = name
def getName(self):
return self.name
============== c.py ==============
def getName():
return "양파개발자"
============== d.py ==============
def getHometown():
return "전주"
※ /home/lib/__init__.py 생성 후
============== a.py ==============
from b import Human
from c import getName
from lib.d import getHometown
human = Human("Jack")
print human.getName()
print getName()
print getHometown()
2. 사용 명령어
2.1 dir
- 모듈을 포함해서 모든 속성을 출력한다.
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_os', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_os', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
2.2 help
- 지정된 함수에 대한 설명을 들을 수 있다.
>>> help(random.randint)
Help on method randint in module random:
Help on method randint in module random:
randint(a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
Return random integer in range [a, b], including both end points.
3. 기본 문법
3.1 블록 생성
- C 또는 java와 비교할 때, 대괄호 ( {, } )를 통해서 지정되는 조건/반복문의 블록
- Python에서는 이런 블록을 스위트(suite)라고 지칭하며 들여쓰기를 통해서 표시한다.
if (조건문) :
call a // if의 suite시작.
call b
call c // if의 suite 끝
3.2 for 반복문
조건문은 콜론(:)를 통해서 구분 된다.
문자/숫자의 사용에서 차이점이 없다. 동일한 방식으로 사용하면 숫자/문자를 자동으로 확인/사용할 수 있도록 제공한다.
range()등의 기본 내장 함수를 사용하며 반복문의 구현이 가능하다.
for (조건) :
실행
3.3 range
- 범위 입력에 사용된다.
- range( stop ) : 0~ stop까지의 정수를 입력
>>> list(range(5))
[0, 1, 2, 3, 4] // 0부터 5보다 작은 정수
[0, 1, 2, 3, 4] // 0부터 5보다 작은 정수
- range(start, stop, step) : start 부터 step의 간격으로 stop까지의 정수 입력
>>> list(range(0,10,2))
[0, 2, 4, 6, 8] // 0부터 2간격으로 10보다 작은 정수의 list
[0, 2, 4, 6, 8] // 0부터 2간격으로 10보다 작은 정수의 list
반응형
'스터디자료 > Python 스터디' 카테고리의 다른 글
[Python] Word문서에서 Excel로 데이터 추출하기 (0) | 2021.03.26 |
---|---|
ch2 - 리스트 데이터 (head first python - 개정판) (0) | 2018.09.29 |
python study 시작과 최종 계획 (0) | 2017.12.29 |