python 기초 문법 정리
Life is short, You need python!
환경: python 2.7
위키 :
http://ko.wikipedia.org/wiki/%ED%8C%8C%EC%9D%B4%EC%8D%AC
https://mirror.enha.kr/wiki/Python
소개
https://docs.python.org/2/tutorial/introduction.html
** 주의 : 들여쓰기 --- 탭, 공백 중 한가지만으로 일관성있게 해야함.
안그러면, 에러!!!!!
; 다른 소스 복사해 올때 특히 주의 !!!
** 파이썬 내장함수 https://docs.python.org/2/library/functions.html#
1. number # 숫자 - int, float, complex
https://wikidocs.net/12
+, - , * , /
// --> 몫
% --> 나머지
divmod(9,4) --> 몫, 나머지
x**y --> x 의 y 승
>>> a = 34
>>>
>>> type(a)
<type 'int'>
>>>
>>> isinstance(a, int)
True
>>>
>>> float(a)
34.0
>>>
>>> str(a)
'34'
>>>
>>> complex(a)
(34+0j)
>>>
>>> bin(34)
'0b100010'
>>>
>>> oct(34)
'042'
>>>
>>> hex(34)
'0x22'
>>>
>>> b = 0b11011 # 2 진수
>>> c = 0o34 # 8 진수
>>> d = 0x34 # 16 진수
>>>
>>> print b, c, d
27 28 52
>>>
>>> print(b,c,d)
(27, 28, 52)
>>> type(d)
<type 'int'>
>>> 032 + 1
27
>>> 032
26
>>> 0o32
26
>>> 0x34 + 1
53
>>>
>>> b = '123'
>>> print b
123
>>> repr(b)
"'123'"
>>> type(b)
<type 'str'>
>>> a = 123
>>> print a
123
>>> repr(a)
'123'
>>> type(a)
<type 'int'>
>>> b
'123'
>>> a
123
>>>
2. string # 문자열
참고 : https://wikidocs.net/13
-- a='abcdef', b="abc"

>>> len(a)
6
>>> a[3]
'd'
>>> a[-2]
'e'
>>> a[0:-2] # 0 <= < 2
'abcd'
>>> 'ab' + 'kk'
'abkk'
>>> a=124
>>> str(a)
'124'
>>> int('234')
234
>>> str(123.222)
'123.222'
>>> float('123.222')
123.222
>>> ord('a') # ascii 코드 숫자 반환하는 내장함수
97
>>> hex(97)
'0x61'
>>> oct(97)
'0141'
>>> bin(97)
'0b1100001'
>>> int(0x61)
97
>>> int('0x61')
Traceback (most recent call last):
File "< pyshell#58 >", line 1, in <module >
int('0x61')
ValueError: invalid literal for int() with base 10: '0x61'
문자열 포맷팅
참고 : https://wikidocs.net/13
https://mkaz.com/2012/10/10/python-string-format/
https://docs.python.org/2/library/string.html#format-examples
>>> 'int(%s)'%'0x61' # %s --> 문자열로 변환 ;; 문자열 포맷팅
'int(0x61)'
>>> eval('int(%s)'%'0x61') # 문자열로 된 Expression(식) 실행, (비교) exec
97 # http://freeprog.tistory.com/6 참조.
>>> '--%d-- is conveted to --%x--'%(15,15) # %d --> 십진수 , %x --> 16진수 소문자..
'--15-- is conveted to --f--'
>>> '%04d is conveted to --%2X--'%(15,15) # %04d --> 십진수, 최소4칸 확보, 좌측빈칸은 0으로채움.
'0015 is conveted to -- F--' # %2X --> 16진수 대문자.., 최소 2칸 확보...
>>> 'I am %s' % 'Tom'
'I am Tom'
>>> 'movie title is %s and %s' % ('Tom','Jerry')
'movie title is Tom and Jerry'
>>> a= 'I am a boy'
>>> a.split()
['I', 'am', 'a', 'boy']
>>> b= a.split()
>>> b
['I', 'am', 'a', 'boy']
>>> ','.join(b)
'I,am,a,boy'
>>> t= 'I,am,a,boy'
>>> t.split(',')
['I', 'am', 'a', 'boy']
>>> ''.join(t.split(','))
'Iamaboy'
>>> ' '.join(t.split(','))
'I am a boy'
list # 리스트
참고 : https://docs.python.org/2/tutorial/datastructures.html
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a
[66.25, 333, -1, 333, 1, 1234.5]
>>>
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5]
>>>
>>> a.reverse()
>>> a
[1234.5, 1, 333, -1, 66.25]
>>>
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 1234.5]
>>>
>>> a.pop()
1234.5
>>> a
[-1, 1, 66.25, 333]
>>>
>>> del a[0]
>>> a
[1, 66.25, 333]
>>>
>>> a[-1]
333
>>> a[:]
[1, 66.25, 333]
>>> a
[1, 66.25, 333]
>>>
>>> a[0:2]
[1, 66.25]
>>> a[-2:]
[66.25, 333]
>>>
>>> k = range(10)
>>> k
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> k[::2]
[0, 2, 4, 6, 8]
>>> k[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> k[:5]
[0, 1, 2, 3, 4]
>>>
tuple # 튜플 --- 변경불가능 자료...
https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences
>>>
>>> t = 12345, 54321, 'hello!'
>>> t
(12345, 54321, 'hello!')
>>> t[-2]
54321
>>>
>>> t[-1]
'hello!'
>>> t[-1][:3]
'hel'
>>>
>>>
>>> u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) # Tuples may be nested:
>>>
>>>
>>>
>>> t[0] = 88888 # Tuples are immutable:
Traceback (most recent call last):
File "<pyshell#216>", line 1, in <module>
t[0] = 88888
TypeError: 'tuple' object does not support item assignment
>>>
*** python 에는 상수를 정의하는 문법이 없다.
하지만 PEP8 naming convention 에 따라 대문자 와 _ 을 사용하여 대개 표현한다.
참고 : https://www.python.org/dev/peps/pep-0008#constants
Constants are usually defined on a module level and written in all capital letters with underscores separating words.
예) MAX_OVERFLOW, TOTAL.
*** 마찬가지로, 상수형 자료를 표현하고 싶으면 tuple 을 사용하라! (변경 불가능한 자료이므로)
dictionary # 사전 --- 순서가 없다..
-- { key:value, key:value,...} # key = 유일한 값...(중복 안됨)
>>> mydic = {1:'apple',2:'tree','ab':'333','ls':[1,2,5,'abc']}
>>> mydic
{1: 'apple', 2: 'tree', 'ab': '333', 'ls': [1, 2, 5, 'abc']}
>>> mydic[1]
'apple'
>>> mydic[5]
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
mydic[5]
KeyError: 5
>>> mydic[5] = 'add'
>>> mydic
{1: 'apple', 2: 'tree', 'ab': '333', 'ls': [1, 2, 5, 'abc'], 5: 'add'}
>>> mydic.keys()
[1, 2, 'ab', 'ls', 5]
>>> mydic.values()
['apple', 'tree', '333', [1, 2, 5, 'abc'], 'add']
>>> mydic.items()
[(1, 'apple'), (2, 'tree'), ('ab', '333'), ('ls', [1, 2, 5, 'abc']), (5, 'add')]
>>>
boolean --- True, False
>>> 3 == 4
False
>>>
>>> 3 == (2+1)
True
>>>
None
set # 집합
https://docs.python.org/2/tutorial/datastructures.html#sets
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit # fast membership testing
True
>>> 'crabgrass' in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b
set(['a', 'c'])
>>> a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
if ...:
elif ...:
else:
...
Operation
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity
is not negated object identity
== , is 차이점 참고 : http://freeprog.tistory.com/29
*** python 에서는 switch 문 없다. --> if .. elif .. 문을 사용하라!
for ... in ....: --> enumerate() 자주 사용.
-- continue, break
else: # 정상 for 문 종료시 실행함.
*** python 에서 for 문은 타 언어의 for each 문과 같다.
-- 타 언어의 for 문은 while 문을 사용하라!
>>> for k,v in mydic.items():
print k, v
1 apple
2 tree
ab 333
ls [1, 2, 5, 'abc']
5 add
>>> for i in range(5):
print 'test', i
test 0
test 1
test 2
test 3
test 4
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>>
>>> for sx in seasons:
print sx
else:
print '------ normal -------'
Spring
Summer
Fall
Winter
------ normal -------
>>>
>>>
>>> for i, sx in enumerate(seasons):
print i, sx
if i == 2 :
break
else:
print 'normal...'
0 Spring
1 Summer
2 Fall
>>>
>>>
while ...:
-- continue, break
else: # 정상 while 문 종료시 실행함.
>>> i = 0
>>> while i < 5: # 조건이 참인 경우 아래 구문 실행
print 'test', i
i = i + 1
test 0
test 1
test 2
test 3
test 4
>>>
*** python 에서는 do.. while... 문 없다.
함수
--- class 내부에서는 method 라 부른다.
>>> def hap(a, b):
s = a + b
return s + 100
>>>
>>> hap(1,2)
103
>>>
>>> k = hap(1,2)
>>> print k
103
>>>
함수 return 문 없는 경우
>>> def hap2(a, b): # return 문 없는 경우.
s = a + b
>>> hap2(1,2)
>>> k2 = hap2(1,2)
>>> print k2
None
>>>
함수 return 값이 없는 경우
>>> def hap3(a, b): # return 값이 없는 경우.
s = a + b
return
>>> hap3(1,2)
>>> k3 = hap3(1,2)
>>> print k3
None
>>>
**참고 : pass -- 아무것도 하지 않는다. 필요시 추후에 구현할 수도 있다.
>>> def kop():
pass
>>>
>>>
>>> kop
<function kop at 0x02187930>
>>>
>>> kop()
>>>
함수 인수의 기본값 설정하기
>>> def myfx(a, x = 3):
print a**x
>>>
>>> myfx(2)
8
>>>
>>> myfx(2,4)
16
>>>
가변인수
- * ; tuple 로 받는다.
- ** ; dictionary 로 받는다.
>>> def test(a, *b, **kw): # 가변인수
print 'a = ', a
if b :
print '*b = ', b
if kw : print ' **kw = ', kw
print
>>> test(123)
a = 123
>>> test(123,555,'test','a','bb')
a = 123
*b = (555, 'test', 'a', 'bb')
>>> test(123,['test','a'],'bb')
a = 123
*b = (['test', 'a'], 'bb')
>>> test(234, 'aa','bb','cc', k=3, y=44)
a = 234
*b = ('aa', 'bb', 'cc')
**kw = {'y': 44, 'k': 3}
>>>
>>>
<< 기본개념 >>
namespace (이름공간) -- a mapping from names to objects ???
모듈 -- python 파일 : a single Python file
팩키지 -- module 모음 폴더 : a directory of Python modules containing an additional __init__.py file
** 근데 사람들은 module, package, library, battery 등의 말들을 같은의미로 사용한다
http://legacy.python.org/dev/peps/pep-0008/#package-and-module-names
-- PEP8 --
Module Names -- short, all-lowercase names
Package Names -- short, all-lowercase names
Class 이름 : 대문자로 시작
method 이름 (함수 이름) : 모두 소문자
====== Module ==============
아래와 같은 내용의 aa.py 파이썬 파일을 만들자
# aa.py
print '.. module..'
print __name__
kk = 3333
print kk
이를 실행시켜보면 __name__ 자리에 __main__ 이 나온다...

python IDLE 에서 aa.py 를 import 시켜보자.
- 모듈로 import 시킬때는 파일 이름에서 확장자(.py) 빼고 사용

# 모듈로 import 시에는 ; __name__ == aa
# 단독실행시에는 ; __name__ == __main__
# aa.py
print '.. module..'
print __name__
kk = 3333
print kk
if __name__ == '__main__': # 단독 실행시만에 실행되는 조건!!! (모듈로 import 시에는 적용안됨.)
print ' I am main prg'
print 'main kk == ', kk
====== 한글 ==============
** 한글 사용하기...
#-*- coding: euc-kr -*-
-- python 2.7 에서는 모듈 맨위줄에 쓰고자하는 코딩을 위 처럼 적어준다.. (2.7은 기본으로 ascii code 사용)
-- but, 3.x 버전과 ironpython 은 기본적으로 unicode 환경이므로 그냥 한글 사용하면 된다..
-- 리눅스, Mac 은 #-*- coding: utf-8 -*-
>>> import sys
>>> sys.version
'2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)]'
>>> sys.getdefaultencoding()
'ascii'
>>>
>>> import sys
>>> sys.version
'3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)]'
>>> sys.getdefaultencoding()
'utf-8'
>>>
<< 파일 다루기 >>
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
https://docs.python.org/2/library/functions.html#open
1. 파일 쓰기
>>> txt = """ abc test
1234..
test end.."""
>>> f = open('test.txt', 'w') # default == text mode, binary mode 시에는 'wb'
>>> f.write(txt)
>>> f.close()
>>>
2. 파일 읽기
>>> f = open('test.txt') # default == read mode & text mode, binary mode 시에는 'rb'
>>> txt = f.read()
>>> print txt
abc test
1234..
test end..
>>> f.close()
>>>
>>> txt
' abc test\n1234..\ntest end..'
>>>
>>> f = open('test.txt')
>>> for x in f:
print x
abc test
1234..
test end..
>>>
>>> f = open('test.txt')
>>> for x in f:
print x,
abc test
1234..
test end..
>>>
*** MSSQL 접속하기..
참고 : https://code.google.com/p/pyodbc/
>>> import pyodbc
>>> conn = pyodbc.connect('DRIVER={SQL Server};SERVER=MYMAIN;DATABASE=testdb;UID=sa;PWD=1234',autocommit=True )
>>> cursor = conn.cursor()
>>> cursor.execute("select * from client")
>>> recs = cursor.fetchall()
** 이와는 별도로 각 database 마다 connection pooling 은 구글 검색하면 나옵니다....
*** 참고 사항
StringIO : streaming 자료 다룰때 사용할수있는 file-like object
<< Class >>
참고 : http://freeprog.tistory.com/36
<< GUI >>
wxpython 참고 사이트
http://xoomer.virgilio.it/infinity77/wxPython/APIMain.html
http://www.blog.pythonlibrary.org/
http://zetcode.com/