노력과 삽질 퇴적물

파이썬3: 기초정리(2) 본문

프로그래밍note/언어. 스크립트 계열

파이썬3: 기초정리(2)

MTG 2018. 5. 18. 15:44

* 윈도우10(64bit), 3.6.x기반입니다.


파이썬3: 기초정리(1)

파이썬3: 기초정리(2)

파이썬3: 기초정리(3)

파이썬3: 기초정리(4)






1. 자료형


* 파이썬에서 세미콜론은 생략이 가능하지만, 기존에 다른언어에서 쓰던 습관대로 사용했을뿐입니다.


1) 기본 자료형

① 숫자

1
2
3
4
>>> print(2+2);
4
>>> print(2+2.0);
4.0
cs


② 문자열

> 선언을 문자열로 했어도. var[2]처럼 인덱싱이 가능.

1
2
3
4
5
6
7
8
>>> abc = "123456 ";
>>> print(abc);
123456 
>>> defg = 'qwerty';
>>> print(defg);
qwerty
>>> print(abc+defg);
123456 qwerty
cs


③ bool

1
2
3
4
5
6
>>> 1 == 1
True
>>> 1 == 1.0
True
>>> 1 != 1.0
False
cs



2) 길이가 있는 자료형

① 리스트

> 중복값 가능, 순서보장O.

> 유용한 함수

: append(), sort(), reverse(), index(), insert(), remove((), pop(), count(), extend()

> enumerate로 리스트 원소를 하나씩 뽑아서 사용도 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> datas = [];
>>> numbers = [2,0,1,8,5,15];
>>> datas.append("start");
>>> print(datas);
['start']
>>> datas.append(2018);
>>> print(datas);
['start'2018]
>>> datas.append(numbers);
>>> print(datas);
['start'2018, [2018515]]    #리스트 구성원에 자료형 통일필요X
>>> print(datas[0]);
start
>>> print(datas[1]);
2018
>>> print(datas[2]);
[2018515]
>>> print(datas[1:2]);
[2018]
>>> print(datas[0:2]);    #[idx:idx부터 몇번째 슬롯까지]
['start'2018]
>>> datas.clear();
>>> print(datas);
[]
cs


② 튜플(Tuple)

> 리스트를 상수처럼 사용하는 방식

> 중복값 허용, 순서보장O

> 인덱싱, 슬라이싱, 병합, 반복 가능.

> 유용한 함수

: union(), difference(), add(), update(), remove()

1
2
3
4
5
6
7
8
9
10
11
>>> data1 = ();
>>> data2 = ('new ',);    #오타가 아니고, 길이가 1인 경우 내부에서 콤마로 끝난다.
>>> data3 = ('normal''rare''SR''SSR');
>>> print(data2);
('new ',)
>>> print(data3);
('normal''rare''SR''SSR')
>>> print( data2[0]+data3[2] );
new SR
>>> print( data2+data3 );
('new ''normal''rare''SR''SSR')
cs


③ 집합

> 중복값 불가, 순서보장X. (순서가 무작위)

> 파이썬 2.3부터 지원되기 시작

1
2
3
4
5
6
7
8
9
10
11
12
>>> dataSet = set([]);        #CASE. 잘못된 집합선언
>>> dataSet;
set()
>>> dataSet = set([2,0,1,8,0,5,0,5]);        #CASE. 리스트(숫자)로 집합 선언
>>> dataSet;
{01258}
>>> dataSet2 = set("Hello world! & Saluton mondo!");    #CASE. 문자열로 집합 선언
>>> dataSet2;
{'e''H''!''a''w''t''o''n''r''d''l'' ''u''S''m''&'}
>>> dataSet2 = set(["Hello world! & Saluton mondo!"]);    #CASE. 리스트(문자)로 집합 선언
>>> dataSet2;
{'Hello world! & Saluton mondo!'}
cs


④ 딕셔너리

> key-value로 입출력

> key 중복불가, 순서보장X. (순서가 무작위)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> dataDic = {}   #빈 딕셔너리
>>> dataDic;
{}
>>> dataDic['abc'= 'QWERTYU'
>>> dataDic['ABC'= 'zxcvbnm'
>>> dataDic['abc'];
'QWERTYU'
>>> dataDic['ABC'];
'zxcvbnm'
>>> dataDic;
{'QWERTYU''zxcvbnm'}
>>> dataDic = {'word1':'word1 is something''world2':'it is not word1'}   #한번에 선언하는 방법
>>> dataDic = {'hair':'black''eyes':'brown''blood':'A'}
>>> dataDic.keys();
['hair''eyes''blood']
>>> dataDic.values();
['black''brown''A']
cs






2. 연산자


1) 연산자

 나누기(소수점)

/

예.

>>> print(7/2);

3.5

>>> print(8/2);

4.0

 나누기(정수)

//

예.

>>> print(7//2);

3

>>> print(8//2);

4

 제곱

**

 8 == 2 ^ 3 (C/C++ 및 JAVA등등)

   == 2 ** 3 (파이썬 스타일)

 그외.


 축약연산자 및 사칙연산자는 다른 언어와 동일.



2) 기타

 출력문 정렬

예시.

 %10s //문자열 10칸에서 우측정렬

 %-10s //문자열 10칸에서 좌측정렬

 %0.4f //소수점 4자리까지






3. 제어문


* 파이썬에는 switch-case문이 없습니다.


1) 조건문

> if-elfi문에는 조건문이 아닌 조건문 내용과 같은 깊이의 들여쓰기이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> idx = 2018;
>>> if idx == 2017:
...     print('정유年');
... elif idx == 2018:
...     print('무술年');
... else:
...     print('범위외');
... 
무술年
>>> idx2 = "this_is_string";
>>> if idx2 is 'this_is_string':
...     print('따옴표 조건문 블록');
... elif idx2 is "this_is_string":
...     print('쌍따옴표 조건문 블록');
... else:
...     print('범위외');
... 
따옴표 조건문 블록
cs



2) 순환문

① while문

1
2
3
4
5
6
7
8
9
10
11
12
>>> idx = 0;
>>> LIMIT = 5;
>>> while idx < LIMIT:
...     print(idx);
...     idx+=1;
...     pass;   #end, while idx < LIMIT:
... 
0
1
2
3
4
cs


② for문

> pass문?

: C/JAVA와 달리 {...}가 없는 형태라 블록이 끝나는 위치를 명시하는 용도로도 가능.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
>>> idx = 0;
>>> datas = [2,0,1,8,5,30];
>>> loopRange = range(1100);
>>> for idx in loopRange:
...     if (idx in datas) == False:
...         idx+=1;
...         #sample for continue
...         continue;
... 
...     print("----------");
... 
...     if idx in datas:
...         print(idx);
...         idx+=1;
...         pass;
...     print("==========");
...     pass;   #end, for idx in loopRange:
... 
----------
1
==========
----------
2
==========
----------
5
==========
----------
8
==========
----------
30
==========
cs



3) 에러처리

1
2
3
4
try
    # do-something
except ZeroDivisionError as err: 
    print(err);
cs






4. 함수와 클래스


1) 함수

> 함수끝에 pass가 아닌 [return resultVal;]을 쓰면 함수내에서 처리한 결과값을 호출한곳으로 사용가능.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> def SimpleLog():
...     print("This is simple print");
...     pass;
... 
>>> def ParameterLog(msg):
...     print("This is simple print [%d]" % msg);  #문자열이면 %s
...     pass;
... 
>>> def ComplicateLog(msg1, msg2):
...     print("This is %s print [%s]" % (msg1, msg2));
...     pass;
... 
>>> SimpleLog();
This is simple print
>>> ParameterLog(2018);
This is simple print [2018]
>>> ComplicateLog("Mess@ge"10);   #내부상, 자료형 변환이 자유로운편이라 가능.
This is Mess@ge print [10]
cs



2) 클래스

① 기본적인 사용: 선언, 메모리 삭제, 멤버함수 호출

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#   ===============================================================
#   클래스 정의
#   ===============================================================
class DevTool:
    def __init__(self):
        #생성자
        print("DevTool, called __init__()");
        pass;
    def __del__(self):
        #소멸자
        print("DevTool, called __del__()");
        pass;
 
    def SimpleLog(self):
        print("DevTool, This is simple print");
        pass;
 
    def SingleParameterLog(self, msg):
        print("DevTool, This is simple print [%d]" % msg);  #문자열이면 %s
        pass;
 
    def MultipleParameterLog(self, msg1, msg2):
        print("DevTool, __%s__   __%s__" % (msg1, msg2));
        pass;
    pass;   #end, class LogTool:
 
class DebugTool(DevTool):
    # LogTool클래스를 상속받은 자식클래스.
    def SimpleLog(self):
        #OOP. 오버라이드된 함수.
        #super().SimpleLog();   #기존함수 기능도 포함이 필요할 경우.
        print("DebugTool, This is simple print");
        pass;
    pass;
#   ===============================================================
 
 
_log = DevTool();   #자바 or C++식으로 하면 UsrObect usr_object = new UsrObect();
print("------------------------------");
_log.SimpleLog();
_log.SingleParameterLog(2018);
_log.MultipleParameterLog("saluton""mondo");
print("------------------------------\n");
del(_log);
cs

> 결과

1
2
3
4
5
6
7
8
9
DevTool, called __init__()
------------------------------
DevTool, This is simple print
DevTool, This is simple print [2018]
DevTool, __saluton__   __mondo__
------------------------------
 
DevTool, called __del__()
계속하려면 아무 키나 누르십시오 . . .
cs


② 객체지향

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#   ===============================================================
#   클래스 정의
#   ===============================================================
class DevTool:
    def __init__(self):
        #생성자
        print("DevTool, called __init__()");
        pass;
    def __del__(self):
        #소멸자
        print("DevTool, called __del__()");
        pass;
 
    def SimpleLog(self):
        print("DevTool, This is simple print");
        pass;
 
    def SingleParameterLog(self, msg):
        print("DevTool, This is simple print [%d]" % msg);  #문자열이면 %s
        pass;
 
    def MultipleParameterLog(self, msg1, msg2):
        print("DevTool, __%s__   __%s__" % (msg1, msg2));
        pass;
    pass;   #end, class LogTool:
 
class DebugTool(DevTool):
    # DevTool클래스를 상속받은 자식클래스.
    def __init__(self):
        #생성자
        print("DebugTool, called __init__()");
        pass;
 
    def SimpleLog(self):
        #OOP. 오버라이드된 함수.
        #super().SimpleLog();   #기존함수 기능도 포함이 필요할 경우.
        print("DebugTool, This is simple print");
        pass;
    pass;
#   ===============================================================
 
 
_log = DevTool();   #자바 or C++식으로 하면 UsrObect usr_object = new UsrObect();
print("------------------------------");
_log.SimpleLog();
_log.SingleParameterLog(2018);
_log.MultipleParameterLog("saluton""mondo");
print("------------------------------\n");
#del(_log);
 
_debug = DebugTool();
print("------------------------------");
_debug.SimpleLog();
_debug.SingleParameterLog(2018);
print("------------------------------\n");
cs

> 결과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
DevTool, called __init__()
------------------------------
DevTool, This is simple print
DevTool, This is simple print [2018]
DevTool, __saluton__   __mondo__
------------------------------
 
DebugTool, called __init__()
------------------------------
DebugTool, This is simple print
DevTool, This is simple print [2018]
------------------------------
 
DevTool, called __del__()
DevTool, called __del__()
계속하려면 아무 키나 누르십시오 . . .
cs


③ 기타

> self

: JAVA의 this처럼 특정함수, 클래스내 변수를 명시하는 예약어(혹은 키워드)격.

: 클래스내 모든 함수의 첫번째 인자는 무조건 self이되, 인자가 있는 함수를 호출시 입력치 않음.

python self 설명 | grayfugitive



3) 가변인자 *args, **kwargs

> 함수를 정의해두면 콘센트처럼 정해준 규격으로 입력을 해야 하는데, 인자의 갯수가 고정이 되어 있기때문에 필요에 따라 인자만 다른 함수가 필요해질수도 있습니다. 이런 상황을 대응케 하는게 가변인자입니다.

> 간단히 정리하면, Asterisk(*)를 1개만 쓰면 튜플형태로, 2개를 쓰면 딕셔너리 형태로

> *args, **kwargs의 경우, 관용적으로 쓰이는 변수명이라고 함.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> def doSum(*args):
...     result = 0;
...     print(args);
... 
...     for i in args:
...         result += i;
... 
...     print(result);
... 
>>> pass;
>>> doSum(20);
(20,)        #함수에 가변인자를 넣으면 튜플로 처리되는걸 확인 가능.
20
>>> doSum(20,1,8);
(2018)
29
>>> doSum(20,1,8,6,5);
(201865)
40
cs


1
2
3
4
5
6
7
8
9
10
11
12
>>> tmp1, tmp2, *args = range(10);
>>> print(tmp1);
0
>>> print(tmp2);
1
>>> print(args);
[23456789]
>>> *args, tmp3 = range(10);    #가변변수에 나머지 값들이 다 들어간다.
>>> print(args);
[012345678]
>>> print(tmp3);
9
cs






5. 모듈과 패키지


1) 모듈

> 변수, 함수, 클래스가 정의되어 있는 소스코드 파일. 모듈로 파일을 분할하면 소스코드를 좀더 간결하게 하는데도 유용.

> 참조

뭉치 가져오기

여러가지 뭉치

# Utility.py

... ... ...

def SimpleLog(self):

print("This is simple print");

pass;

... ... ...

# Main.py

import Utility;   #모듈을 연동.

... ... ...

... ... ...

Utility.SimpleLog();   #연동된 모듈을 사용.

... ... ...



2) 패키지

> 모듈을 디렉토리 구조로 구성케함.

> 디렉토리별로 존재하는 __init__.py는 디렉토리가 패키지에 포함되게 처리한다. 단, 파이썬 3.3부터는 필수X

1
2
3
4
5
6
7
8
9
10
# 패키지 구성 예시.
src/data/__init__.py
   /data/ScoreTable.py
   /data/RandomRule.py
   ... ... ...
   /sprite/__init__.py
   /sprite/Stage.py
   /sprite/Character.py
   /sprite/Effect.py
   ... ... ...
cs

위와같은 패키지 구성일때, 코드에서 사용하려면 3가지 방식이 가능.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 패키지 사용법 1.
import src.data.ScoreTable
... ... ...
src.data.ScoreTable.XxxXxx();
 
 
# 패키지 사용법 2.
from src.data import ScoreTable
... ... ...
ScoreTable.XxxXxx();
 
 
# 패키지 사용법 3.
from src.data.ScoreTable import XxxXxx()
... ... ...
XxxXxx();
cs



3) 파일 입출력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import os;
 
print">>  readline함수 활용." );
#txtFile = open('C:\Python\Python36\LICENSE.txt');
txtFile = open('C:\Python\Python36\LICENSE.txt''r');
print( txtFile.readline() );
print( txtFile.readline() );
print">>  ------------------------------------------------------------------" );
 
print">>  readlines함수 활용." );
txtFile = open('C:\Python\Python36\LICENSE.txt''r');
txtLines = txtFile.readlines();
idx = 0;
for line in txtLines:
    print(line);
    idx += 1;
    if idx==5:
        break;
        pass;
    pass;
txtFile.close();#readlines()후 반드시 close로 마무리.
print">>  ------------------------------------------------------------------" );
 
print">>  read함수 활용." );
txtFile = open('C:\Python\Python36\LICENSE.txt''r');
txtRead = txtFile.read();#파일 전체를 출력.
print(txtRead);
txtFile.close();#read()후 반드시 close로 마무리.
print">>  ------------------------------------------------------------------" );
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>>  readline함수 활용.
A. HISTORY OF THE SOFTWARE
 
==========================
 
>>  ------------------------------------------------------------------
>>  readlines함수 활용.
A. HISTORY OF THE SOFTWARE
 
==========================
 
 
 
Python was created in the early 1990s by Guido van Rossum at Stichting
 
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
 
>>  ------------------------------------------------------------------
>>  read함수 활용.
A. HISTORY OF THE SOFTWARE
==========================
 
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC.  Guido remains Python's
principal author, although it includes many contributions from others.
... ... ...
... ... ...
cs






기타. 참조자료


프로그래머가 아닌 이들을 위한 파이썬 3 자습서/Hello, World - 위키책

점프 투 파이썬 - WikiDocs


파이썬: 기초정리 (2)


파이썬의 Asterisk(*) 이해하기 · mingrammer's note

전문가를 위한 파이썬 - 1 – WinterJ Blog






기타. 변경이력


일자

변경이력

2018-05-18

 초안

2018-06-05

 4. 3) 가변인자 *args, **kwargs  추가

'프로그래밍note > 언어. 스크립트 계열' 카테고리의 다른 글

루아: 기초정리(1)  (0) 2019.05.26
HTML5: cocos2d-js 기초 (1)  (0) 2018.05.23
파이썬3: 기초정리(1)  (0) 2018.05.14
PHP: 기초정리(1)  (0) 2015.04.06
리눅스: catalina.out 백업 스크립트  (0) 2015.01.22